JavaScript Form Validation

JavaScript Form ValidationThis article is an introduction to how to create good form validation with javascript. I will briefly describe the interaction pattern of client side validation with javascript. Later I will focus on 10 actions that will make your form validation perfect.

The Design Pattern of Client Side Form Validation

Whenever a user needs to submit data to your application, there is a need in validating the users input.

Top 10 tips for JavaScript Form Validation

Use a form validation framework or a form validation library

I strongly recommend using some kind of JavaScript-library or framework when implementing your client side validation. On top of that it is important to use/implement a validation framework, this is because you will have bugs and issues with your client side validation, and a framework makes it easier addressing these bugs and issues. When we changed client side validation on a redesign of a larger site lately, we built the validation framework on top of the jquery javascript library. That architecture has made it easier addressing issues and bugs that do arise during development and maintenance of your forms.

Focus on solving the big validation problems

As soon as you start developing and implementing your validation, it is easy trying to address all potential validation that is needed for all types of input. My advice is to try to catch 75-85% of the potential user input errors in the front-end validation. Trying to catch all will lead to the following:

  • Bloated code, your framework will grow too large
  • More or less impossible to test client side validation as there are too many combinations of validation that can go wrong
  • Business rules will move to the front-end.(More on how to avoid this by using Ajax later)

To avoid this I think that creating a small validation framework that can do most of the validation is the way to go, and leave the specific things for the server (or create a plugin to your framework later) to validate.

Do Form Validation before form is submitted

The traditional JavaScript form validation pattern used since the 1995+ is to validate the form when the user hits the submit button, and whenever the script encounter a form item with some error in it, focus on that form item and prompt the user with an JavaScript-alert saying that something went wrong.Today, there is no need doing it that way.In your pursuit of creating the perfect front-end validation framework, you must add the possibility to validate controls on other events than just submitting. I see these potential events:

  • Whenever a controls value is changed
  • When a control is blurred
  • Periodically check if controls has changed
  • When a control that is connected to another control changes value
  • When a form is submitted
  • When a form is reset (if you for some reason finds it intelligent to have a reset-button on your form)

Use Ajax Form Validation for business data input

In order to validate business data you have three alternatives

  • Let the server take care of it
  • Add business logic to your front-end code
  • Let the front-end talk to the back-end through an Ajax-API

My suggestion is to go with the first or the last option, if you go with the last option there are a couple of things to keep in mind

  • Make sure your code is secure. Sometimes “smart” solutions like these, exposes business data to people with a little technical knowledge
  • Create a server-side API that has a defined set of methods with a defined set of parameters to be sent to it.
  • Create a client-side wrapper, wrapping the functionality exposed in the server-side API.
  • Only allow communication between the server-API and the client-side API-wrapper
  • Make your API-responseType configurable, sometimes you want to show the result as HTML, sometimes you want to manipulate the answer within your JavaScript code and sometimes you will use the response for more queries. I think that the API at least must be able to response with these types:
    • json
    • html
    • xml
    • script
    • text

Typical business data in my mind, are unique usernames and emails, age-validation rules, address verification etc etc

Do extensive testing of your javascript form validation

There is one thing worse than no validation: Validation that do not let correct data through.In order to avoid this, my finding is that coding is a smaller part then the actual testing of the validation framework. My tips is to create unit-tests for all your validation rules as a part of the validation framework, this way it is easy for you/your team to verify functionality whenever a change is needed to your framework

Rewrite input data to valid formats

Some input will come in different formats, dates for example. JavaScript Form Validation should address this problem by rewriting from known invalid formats to the valid format. An example can be:20070325 -> validation rewrite format -> 2007-03-25Because the user has not made an error, he/she has given the system a correct date, it is not his/her problem if the system doesnt use his/her format. The system should then be able to rewrite the known wrong format (20070325) to the system correct format (2007-03-25). Typical areas where reformatting can be used

  • Dates
  • Time
  • Phone numbers
  • Social Security numbers / Personal Numbers
  • Trim spaces
  • Remove/exchange invalid characters

Attach javascript form validation late in the design process

Semantic webs must be able to present forms that do validate and function without the attachment of behavior, which is the case when adding JavaScript Form Validation. Therefore I think it is important to make sure your use-cases is valid with or without the adding of client side validation. If you make sure this is valid, there will be small problems making sure the web is ready for mobile users and search engines.

Make the script i18n- and l10n-compatible

If your web is successful for an international public, the non-english-speaking audience is next. In order to achieve this it is important that even user generated error messages is localised and translated. Make sure your client side validation framework is prepared for translation and other localised parameters such as currencies, dates and time-formatting.

Add callback functions to validator framework

90 % of the time you want to use your validation framework as it was intended to be used, 10 % of the time you will be wishing that your framework would be more generic to achieve some specific interesting effect you have identified while working with your site and validation framework. In order to achieve this I think it is important to add the possibiltity to attach callback functions for your forms, letting the developer use your library in a way you couldnt dream of. The definition of a good library is when people using it creates stuff you as a creator of the library didnt think was possible.

Make your framework/library extensible

If you add working hours to a framework or a library, it is important that the architecture of the library/framework is open, and is extendable.

Resources

Related posts

This entry was posted in Featured, JavaScript and tagged , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

4 Comments

  1. udayabhaskar
    Posted September 13, 2007 at 5:16 am | Permalink

    nice to see ur site.as i was new to script programmer i will utilize this site to make a form with live validations.

  2. Posted February 11, 2008 at 6:21 am | Permalink
  3. Posted October 27, 2008 at 1:18 pm | Permalink

    Awesome, just what I need…

  4. Posted August 23, 2009 at 10:50 pm | Permalink

    How can i download this script. I want to use it my own website.

13 Trackbacks

  1. By Подробно on February 9, 2010 at 1:10 am

    следовало ожидать, за релизом 1.1.3 последовал почти мгновенный багфикс 1.1.3.1 [IMG :) ] ) Заметка о валидации форм на стороне клиента, со ссылкой на полезную статью. Я как раз тут ковырял эту тему: валидация форм. Правда я решил делать сразу проверку через php-сторону, чтобы там всё что надо по базе

  2. By jQuery: The Write Less, Do More, JavaScript Library on February 9, 2010 at 1:10 am

    There is a good article about client-side form validation on the Interaction Design Blog. It describes important points to keep in mind when building your own framework for client-side validation. Of course the alternative to building your own framework is to use an

  3. By Let me have a blog on February 9, 2010 at 1:10 am

    for server-side validation, using frameworks (CodeIgniter for PHP or Apache Wicket for JAVA are some examples of web forms validation routines) or programming all the code lines for to validate the input data from the user. But there are some thoughts about you prefer validate also the web form in the client side: Is faster. You don’t need send the form and wait the response from the server. Major interactivity. More usable interfaces. In internet, there are some examples of different sort of

  4. [...] on jQuery form validation is specific. Read more about javascript form validation in my post: Form Validation with JavaScript published [...]

  5. By bassistance.de on July 4, 2007 at 12:59 pm

    About client-side form validation and frameworks…

    There is a good article about client-side form validation on the Interaction Design Blog. It describes important points to keep in mind when building your own framework for client-side validation.
    Of course the alternative to building your own framew…

  6. By はてなブックマーク - タグ javascript on September 9, 2007 at 10:12 pm

    [...] Bookmark.push(‘entry-5835684′) Form Validation with JavaScript – The Frontend hising.net ウェブ   Ajax client JavaScript POSSIBILITY script 1 users [...]

  7. [...] form validation done Right. Next to each required field was a red circe with an X in white. Form Validation with JavaScript – The FrontendThis article is an introduction to how to create good form validation with javascript. I will [...]

  8. [...] favicon, development tools, Java, sql basics, building web sites, and much more for developers. Form Validation with JavaScript – The Frontend User centered development and JavaScript, jQuery, smarty, interaction design, user interfaces [...]

  9. By Dynamik in Formularen : Einfach für Alle on October 21, 2007 at 8:35 am

    [...] hising: »JavaScript Form Validation Overview« [...]

  10. By George's Blog - Archives for: 2007 on February 13, 2008 at 3:12 am

    [...] http://bassistance.de/2007/07/04/about-client-side-form-validation-and-frameworks/ 参考: http://hising.net/blog/form-validation-with-javascript 这里有表单验证的jQuery插件:http://bassistance.de/category/jquery/ [...]

  11. [...] recently I came across with a excellent article about form validation with JavaScript by Mattias Hising (actually the article was posted last year..:P), which leads me to a reusable [...]

  12. By All my bookmarks ever | Daniel John Gayle on May 29, 2009 at 4:54 pm

    [...] Form Validation with JavaScript – jQuery Examples | Front End Book [...]

  13. [...] of client-side form validation on the web and wrote a piece on the subject a couple of years ago, best practices for web form validation, and last week I noticed a peek in traffic as I was linked (somewhat hidden though) from an article [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>