tutorials:~ How to validate forms

How to validate forms?

Forms can be tedious to handcode. However, the job is not done until the form is not collecting the data users enter. As a form creator, it is your responsibility to ensure that the content of the form is formatted correctly. That’s why we prepared some tips on how to tackle the form validation.

Always validate forms on the server

Remember that the HTML attributes and Javascript can be edited in browser and form behavior altered, so always check on the server as well. But for better user experience you should still validate the input information client-side as well (using Javascript and HTML5) so that users get immediate and specific feedback what went wrong with their form filling out process.

What can you do on HTML5

  • Required attribute on inputs - will prevent a form from submission if the specified form fields are empty and display the neat message next to form inputs which have this attribute
  • Use Input types. They are good both for visual UI and validation.
  • Style valid/invalid inputs using CSS
    p {
    input:required:invalid, input:focus:invalid {
    /* insert your own styles for invalid form input */
    -moz-box-shadow: none;
    input:required:valid {
    /* insert your own styles for valid form input */
  • Use input patterns for different data types, use the title attribute to customize the error message

Sample JS function for form validation

This is a sample JS function for form validation. It doesn’t use the HTML5 required attribute. This case may be useful if you want to add custom validation and/or send form data via AJAX.

The validateOneInput() function checks if any input is empty and if the email field contains specifically‘@’ character. It checks each input on change and the whole form on submit.  One of the benefits of it is that the error messages are displayed under each input and that each field is checked after it was edited. Because validateOneInput() checks each input individually, you don’t get “empty field” errors in the fields you haven’t started filling out yet. When the user submits the form, the validate() function loops through all form elements and validates each of them using validateOneInput().

You can add your validation rules for each input type to the validateOneInput() function, as well as styling for invalid inputs. Happy tweaking!

Ana Makarochkina

After a long journey in cultural studies and management science, Ana realized that code speaks louder than words. Since that time her major areas of focus are Vim, React, and Tachyons. She likes to wr... more about Ana Makarochkina