Home / Articles / Programming languages / Markup languages / HTML & CSS / Form validation in HTML5

Form validation in HTML5

Form validation in HTML5
 
  • Currently 0 out of 5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Rating: 0/5 (0 votes cast)

Thank you for rating!

You have already rated this page, you can only rate it once!

Your rating has been changed, thanks for rating!

Log in or create a user account to rate this page.


Form fields are designed to collect information from visitors of a certain page. But despite the best efforts and explanations, getting the correct information from an average user can be difficult. Impatient or careless visitors may miss important fields, only partially fill one or several fields, or simply press the wrong keys. After filling the form this way they click "Send" button. The server program receives a set of data and if data validation is not implemented on the server side, the server program has no idea what to do with it.

A professional web page requires data validation, i.e. a method for detecting errors in the input data, or even better - a way to avoid mistakes in the first place. Over the years, web developers have been doing this using JavaScript procedures of their own design or through professional JavaScript libraries. To be honest, these approaches gave excellent results.

But, after noticing that the validation is performed everywhere (practically every site needs to validate the entered data looking for errors) and also that it is being applied only to a few basic types of data (e.g. e-mail addresses and dates), and that its implementation is so tedious and boring task (no one likes to write the same code for every form, not to mention testing it) people thought that there should be a better way to implement it.

HTML5 creators were able to see this need and have invented a way to call browsers to everyone's rescue by shifting the burden of verifying data from the shoulders of web developers to web browsers. HTML5 creators have developed a client-side validation, which allows to embed basic validation rules in any input field. And the best part is that it's simple and easy: all you need to do - so it is to insert the needed attribute.

How does the HTML5 validation work?

The basic idea behind HTML5 validation form is that the developer specifies the validation data, but does not concern himself with all the necessary time-consuming details. This is similar to a boss who only gives orders, but doesn't implements these guidelines himself, but with the help of his employees.

For example, let's imagine an instance when a particular field can not be left blank, and the visitor must fill it with something. In HTML5, this is realized by using the attribute required in an appropriate field:

<input id="username" placeholder="John Jones" required>

Even with the use of the attribute required for the field, this requirement (necessity of filling the field) by default has no visual pointers (indicators). Therefore, the developer should point this requirement out to the user by using any of the special visual cues, such as special frame field color and putting an asterisk next to it.

Validation is performed when the user clicks the button to submit the form. If your browser supports HTML5 forms, it notices an empty required field, then it intercepts the form being sent and displays a pop-up error message:

Example 1

Although formal requirements what to display in an error messages when validating don't exist, all browsers use for this purpose pop-up tips. Unfortunately, web developers can not change the appearance or the text of the message (without using JavaScript), at least not at the moment.

Another question pops up: what would happen if several rules of validation were violated, for example, several required fields were not filled?

Again, nothing would happen until the user clicks the submit form button. Only after clicking does the browser begin to validate the fields from top to bottom. When encountering an invalid value, it stops further validation, intercepts form submission and displays error message next to the field that caused the error. Even more, if after filling out the form the error message has moved beyond the screen, the browser scrolls the screen in a way that the message is displayed at the top of the page. After the user corrects the error and again clicks the submit form button, the browser continues until the next error entry and the process repeats.

How to turn off validation

In some cases, you may want to disable the validation. For example, you want to test your server-side code on how to correctly deal with the received incorrect data. To disable validation for the entire form, into element form add attribute novalidate:

<form action="/feedback" novalidate>
  ...
</form> 

Another approach is to disable validation inside the submit form button code. For example, instead of sending, one may be required to save the form half-filled for further use. To make this happen, in the input element of the corresponding button attribute formnovalidate is inserted:

<input type="submit" value="Send information" formnovalidate>

Blank field detection is only one of the several types of validation. Later, we'll talk about the detection of data errors of different types.

How to mark the results of validation

Even though web developers can not change to their bidding validation error messages, they can change the appearance of fields depending on the validation results. For example, you can change background field color with an invalid value immediately after the browser detected incorrect data.

All you need is to add a few simple CSS3 pseudo classes. Following options are available:

  • required and optional - apply formatting to the field depending on whether or not this field uses the attribute required;
  • valid and invalid - apply formatting to the field depending on the correctness of the entered value, but do not forget that most browsers don't validate data until the user tries to submit the form, so the formatting of fields with incorrect values is not displayed immediately upon the values input;
  • in-range and out-of-range - apply formatting to the fields that use attribute min or max, to limit their values to certain range of values.

Example:

input:required:invalid {
  background-color: #DEABB3;
}
Example 2

Validation using regular expressions

The most powerful (and most difficult) HTML5 supported validation type is based on regular expressions. Because JavaScript already supports regular expressions adding this capability to the HTML forms was a logical step.

Regular expression - is a template that must be matched with a pattern, coded according to certain syntax rules. Regular expressions are used to search for text strings that correspond to consistent patterns. For example, using a regular expressions, you can validate that zip code contains the correct number of digits, or that an e-mail address has an @ sign, and that its domain extension contains at least two characters. Take, for example, the following expression:

[A-Z]{2}-[0-9]{4}

Square brackets at the beginning of the code define the range of acceptable characters. In other words, the expression [A-Z] allows any uppercase letters from A to Z. Next part in the curly brackets indicates a multiplier, i.e. {2} indicates that there should be only two letters. Then you see a dash; it has no special meaning except itself, i.e. it indicates that after two uppercase letters there should be a dash. Finally, [0-9] denotes numbers from 0 to 9, and {4} means that four such digits are required.

Regular expressions are useful for finding text strings that meet the requirements specified in the expression and to verify that a specific string matches the given pattern set in the regular expression. In HTML5 forms regular expressions are used for validation.

To denote the beginning and end of a value in a field, the characters ^ and $ are not required. HTML5 automatically implies the existence of these two characters. This means that the value in the field must completely match the regular expression so that it can be considered correct.

Thus, the following values are valid for the (above mentioned) regular expression:

AB-1426
QR-4512
WE-0001

But not these: 

ab-1426
QR-14265
5D-2415

But regular expressions if you go deeper into the subject are quickly becoming more complex than in the example above. Therefore, creating a working regular expression can be a quite tedious process, this explains why most developers prefer to validate the data on their pages using ready-to-use regular expressions.

In order to apply your own or ready-to-use regular expression to validate input or textarea field values, the expression should be added as value of attribute pattern:

<input id="email-address" required pattern="\S+@[a-z]+.[a-z]+">
Example 3

Regular expressions seem to be an ideal way to validate email addresses. Moreover, they not just appear to be, but actually are the best thing. On other hand, do not haste to use them this way, because HTML5 already has a separate field type to validate e-mail addresses using a built-in regular expression.

Specialized JavaScript validation

HTML5 specifications also mentions a set of JavaScript properties, which you can use to determine whether fields values are correct (or force the browser to do this validation).

The most useful of these is setCustomValidity method, with it you can write a customized script to validate specific fields, which in turn works with HTML5 validation system.

This is accomplished in the following way. First, value of a field is checked for validity. This is done using ordinary event oninput:

<textarea id="message" oninput="validateMessage(this)"></textarea>

In this example, oninput event activates function validateMessage. The responsibility for writing this function, validating the current input field value and calling setCustomValidity lies solely on the developer.

If there are some problems with the current field value (it's invalid), in that case when calling setCustomValidity method error message needs to be assigned to it. If the current value is valid, this method is run from an empty string, thus canceling the special error messages that may have been used previously.

Below is an example of the method that validates a requirement. In this case that the value is not less than 50 characters:

function validateMessage( input ) {
  if( input.value.length < 50 ) {
    input.setCustomValidity( 'Provide more details.' ); 
  } else {
    // The number of characters is validated, 
    // so we clear the error message
    input.setCustomValidity( '' );
  }
}
Example 4

Of course, this problem can be solved more elegantly using regular expressions, which has a requirement of a long string. But while regular expressions are perfect for validating certain types of data, special validation logic can do practically everything, from complex algebraic calculations to establishing connection with the web server. In other words, it's too versatile.

Web browser validation support

Browser developers were adding validation support to their products in parts, gradually; as a result some browser versions support only certain validation capabilities, but ignore others. The table below lists the minimum browser versions that fully support HTML5 validation:

Browser

IE

Firefox

Chrome

Safari

Opera

Minimum version

10

4

10

5

10

Since HTML5 validation doesn't substitute server validation, it can be considered as an additional option, because even such an imperfect support is better than no support at all. Browsers that do not support validation, such as IE 9, it's possible to send forms with invalid data, but these errors can be detected by the server, then the server can return this page back to the browser, with errors indicated.

On the other hand, your website may contain complex forms in them people usually make a lot of data entry errors, and you do not want to lose those IE-users, which, after the first unsuccessful attempt to fill your form do not wish make another one. In this case, you have two choices: to develop and use your own validation system or to use JavaScript library, to compensate for IE's slow development (snail development). Which of these two approaches to choose depends on the size and complexity of validation.

On HTML5 Cross Browser Polyfills you can find a long list of JavaScript libraries, which in general can do the same trick. Probably one of the best libraries is webforms2.

Webforms2 library implements all the above mentioned attributes. To use the library, download all of the files in the folder of your website (or better in a sub-directory of the website folder) and add the link for this library on the web page.

Webforms2 library goes well with another JavaScript patch, called html5widgets. It supports form features such as slider, date picker and color. Together these libraries provide a good overall support for web forms, but their code contains inevitable oversights and minor bugs. The time will tell whether or not they are well-supported and grinded to perfection.


 

Read also

New types of element input in HTML5

New types of element input in HTML5

Forms in HTML5

Forms in HTML5

Post comment

basicuse.net
html5_css
106160485398655174790

Quick navigation