Form validation development

Original author: Ryan Seddon
  • Transfer

Validation of forms has been a pedantic activity since the advent of the web. Server validation came first. Then it evolved into client-side validation to check the results in the browser. Now we have giants such as HTML5 and CSS3: the chapter on HTML5 forms offers us new types for input fields and attributes that make it possible to check field restrictions. The basic CSS3 UI module provides several pseudo-classes that help us to style the validity state and change the appearance of the field depending on the user's actions. Let's take a look at a combination of both to create a CSS-based form validator that has fairly wide browser support.

The more we can give hints to the user how to fill out the form correctly during the filling process, the less chance that he will make a mistake. Take a look at the CSS3 form validation example in a browser that supports CSS3 UI pseudo-classes like Chrome 4+, Safari 5+, or Opera 9.6+. I used CSS3 UI pseudo-classes and HTML5 form attributes to create CSS-based validation. Let's see how it works.


CSS3 UI pseudo-classes


The UI module contains several pseudo-classes that help stylize form fields depending on their state.
  • valid
  • invalid
  • required
  • optional
  • in-range
  • out-of-range
  • read-only
  • read-write

In the demo shown above, I used pseudo-classes required, invalidand validto perform validation.
input:focus:required:invalid {
  background: pink url(ico_validation.png) 379px 3px no-repeat;
}
input:required:valid {
  background-color: #fff;
  background-position: 379px -61px;
}

* This source code was highlighted with Source Code Highlighter.

Since we want to indicate that the field is not valid only when active, we use a pseudo-class focusto call the style invalidfor the field (Naturally, marking all required fields as invalid from the very beginning will be a bad design decision).

To draw attention to the required fields that have not passed verification, a style is displayed showing an icon with an exclamation mark, which warns the user that something should be entered. After checking the field, if it passes the restrictions, the pseudo-class is validcalled. Now we remove the pseudo-class focusso that the green checkmark indicating the validity of the field remains.

All the values ​​of the pseudo-classes listed above speak for themselves. Pseudo-classes in-rangeandout-of-rangemust be used in combination with attributes minand max, whether it be a field input[type=range]or any other field that accepts these attributes. For example, if a user enters a value that goes beyond the constraints, we can use a pseudo-class to change the style that takes this state into account. In addition, we can do the same if the value falls within the range of restrictions.

Currently, range pseudo-classes only support Opera. In the near future, support will appear in other browsers.

Additional types and attributes helping us


In HTML5 forms, new types are also introduced input, such as email, urland number. For example, it emailcalls a pseudo-class validwhen the user enters the correct e-mail address, the same thing happens for the numerand fields url. Field validation is urldifferent in different browsers. In Opera, typing a "http://"field is indicated by valid, in Crome "http://w", and in Safari, simply typing "http:".

There are several attributes help in the field of verification, such as placeholder, required, maxlength, pattern, min, maxand step.


* This source code was highlighted with Source Code Highlighter.

The postcode field uses a new type numberand several new attributes. In Australia, a zip code can only be 4 digits, so we set an attribute maxlengthto restrict it. We also want to limit the maximum and minimum value of the index, for this we use the minand attributes max. The attribute requiredspeaks for itself (required field).

We can use the attribute step, for more restriction together with minand max. By default, step is set to one. Therefore, any number set in the range between minand maxis valid. If you change the value stepto 100, then the value will be checked in the range from minto maxin increments of 100. For example, the attributestep will be valid for field values ​​1001, 1101, 1201, 1301, etc.

Sample Search


To call a pseudo-class invalidfor a field with more specific restrictions, for example, a phone number for a field, we can use an attribute patternthat allows us to use regular expressions to check the value of the field.




* This source code was highlighted with Source Code Highlighter.


In this example, the regular expression is very simple, "I accept only 10 digits and nothing more." Thus, the field will be invalid until the regular expression is executed. Note that I used the attribute placeholderto give a hint to the user.

In reality, we can set more powerful conditions for the attribute value patternby adding more complex regular expressions, for example, for the password field:


* This source code was highlighted with Source Code Highlighter.

Now we have more stringent restrictions, which allows us to force the user to enter a more secure password. Password must be at least 8 characters, contain one number, one lowercase and one capital letter.

To help the user, we use the attribute title. We do not use the attribute placeholderin this case, since it is intended only for short messages.

Adding Helpful Tips


If the user does not hover over the field, he will never see additional instructions in the attribute title. You may notice that for the fields phone, postcodeand passwordhelpful hints appear, this helps when the user needs additional instructions.



  Minimum 8 characters, one number, one uppercase letter and one lowercase letter
  Your password meets our requirements, thank you.



* This source code was highlighted with Source Code Highlighter.

The markup above contains additional containers for both states - the field is valid and not valid. Thus, when the field is not valid, it will contain information that will help the user enter the correct data. When everything is correct, our message and a green check mark convince him that the field is filled correctly.
.validation01 {
  background: red;
  color: #fff;
  display: none;
  font-size: 12px;
  padding: 3px;
  position: absolute;
  right: -110px;
  text-align: center;
  top: 0;
  width: 100px;
}
input:focus + .validation01 {
  display: block;
}
input:focus:required:valid + .validation01 {
  background: green;
}
input:focus:required:valid + .validation01 .invalid {
  display: none;
}
input:focus:required:invalid + .validation01 .valid {
 display: none;
}

* This source code was highlighted with Source Code Highlighter.

To show or hide the hint, depending on the state of the field, we can indicate to the field a chain of pseudo-classes with the addition of an adjacent element containing the desired hint. After the field has been filled in correctly, the background color changes to green and the corresponding message is displayed.

UX problems of this approach


There is one major problem in using the invalid pseudo-class when a field is required and there are additional conditions that must be met. For example, when a field is required and its type is email, it will not be valid until all its conditions are met and styles will be used invalidfrom the very beginning, even before the user has entered something. That's why we used a pseudo-class focusto show styles invalidonly when this field is in focus. This is not an optimal solution: if a user leaves this field without fulfilling the requirements of the validator, it will not be shown that the data was entered incorrectly until he returns to editing this field.

The solution to this was to add an undefined pseudo-classavailable to radioand checkbox input. Technically, fields that have more conditions than are simply required, while empty are neither valid nor valid, but rather vague. This idea can correct the state invalidand allow you to apply optimal styles for fields depending on the state of validation.

In addition, we can do some pretty big functionality without JavaScript. We can say what state the field has if it is in focus, if necessary, tell it to correspond to a certain pattern specified in the regular expression, indicate the minimum and maximum values, and much more. But what if this is not enough? What if we want more? Fortunately, the chapter on HTML5 forms also defines the validation restriction validation APIs .

Validation Limit Validation API


Along with all the new attributes, input types and CSS3 pseudo-classes, the chapter on HTML5 forms also defines a simple JavaScript API, which allows you to extend the validation of forms with several useful built-in methods, attributes and events. Let's take a look at the updated demo that connects the API to check validation restrictions.

Each form field has a new attribute validity. The attribute validityreturns an object ValidityStatethat provides the current validity state. An object ValidityStatecontains several Boolean variables that determine what state a particular element has. Basically, their answers are true / false which enable the developer to understand what is wrong with the field:
  • valueMissing
    This attribute returns true if the required field is empty.
  • typeMismatch
    Extends to new input types. For example, if the email value is not correct, this attribute will return true.
  • patternMismatch
    If the element contains a pattern attribute and its value does not match the regular expression conditions, the attribute will return true.
  • tooLong
    If the value of an element exceeds its maxlength, this attribute will return true.
  • rangeUnderflow and rangeOverflow
    If the value of an element is outside the min or max attributes, this attribute will return true.
  • stepMismatch
    When an element with the step attribute does not match the required value, this attribute will return true.
  • valid
    If any of the above values ​​returns true, then this attribute will return false. Otherwise, if all the conditions are met, it will return true.

That's not all


The event invalidhas another useful feature. It will be called by the field while its value remains invalid. So, with it, we can change the styles of the fields in accordance with their current state.

In addition, the method checkValidity()can be executed on any single field or the form as a whole, returning true or false.

Applicable to demo


Let's take our previous demo and improve it with the validation restrictions validation API. Taking what we learned from Luke Wroblewski in the Inline Validation in Web Forms article and our own data, we can apply these ideas in our demo form to create an optimal validator.

The first thing we can fix is ​​instant stylization for an invalid field. Instead of immediately changing the style of the field, showing that the user is entering incorrect data, we wait until the user leaves the field.

If the data meets the requirements, even while the field is in focus, we will let the user know that the field is valid. We do this by adding forinputevents for checking the validity of the field. If everything is correct, then we update the styles and show the result immediately.

If the field has an incorrect value, and the user proceeds to the next field, the event blurwill check the validity of the field, and then apply the invalidstyles. So that the user can know about the error. This will preserve the display of error styles until they are fixed.

What about old browsers?


In all topics, new products and support for modern browsers are discussed, all this is good, but let's not forget about the real world, where we must also support outdated browsers. To do this, I wrote a script to help do this.

For browsers that do not support HTML5 forms and the validation restrictions validation API, the script emulates this functionality. For browsers supporting this functionality, the script will determine the availability of support and the functionality will be executed using the browser tools. Let's take a look at the next update of the demo with an added script. Check in IE or Firefox to see the functionality of the script, the same as that of browsers supporting the desired functionality.

Browser support



The script is tested and works in the following browsers:
  • IE6 +
  • Firefox 1+ - FF4 will have built-in support;
  • Chrome 4+ - Native support;
  • Safari 3.2+ - Safari 5 has built-in support;
  • Opera 9.6+ - Native support.

Functions emulated by a script:
  • Each field has an object validitythat makes it possible to know the current state;
  • A method is available checkValidity()indicating that the form or any particular element is not valid;
  • Support attributes placeholder, required, min, maxand step;
  • Support for attributes placeholderand requiredfor textarea;
  • Support requiredfor the item select;
  • Email and urlfor types inputwill be checked using the built-in regular expression.

An abundance of checks


Browser support for HTML5 forms and the CSS3 UI model is starting to improve. Opera9 will continue to support Web Forms 2.0 until they are combined with HTML5 forms. Support appeared in Chrome from version 4, Safari received it recently with the release of version 5, Firefox should add support in the upcoming beta version 4 and IE9, if they continue to develop at this pace, they should also get support.

We can do amazing things with the appropriate CSS3 and HTML5 sections. All browsers improve support and this form verification method becomes viable, able to validate any simple or complex forms.

Also popular now: