JavaScript Form Validation

If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!

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



14 Responses to “JavaScript Form Validation”

Подробно on November 30th, 1999 00:00:

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


jQuery: The Write Less, Do More, JavaScript Library on November 30th, 1999 00:00:

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


Let me have a blog on November 30th, 1999 00:00:

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


JQuery form validation plugin – Interaction Design Blog on March 30th, 2007 22:01:

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


bassistance.de on July 4th, 2007 12:59:

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…


はてなブックマーク - タグ javascript on September 9th, 2007 22:12:

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


udayabhaskar on September 13th, 2007 05:16:

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


Java script form validation, - Javascript Form Validation Code on September 15th, 2007 02:17:

[...] 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 [...]


validate javascript form code verification validation verify on September 23rd, 2007 03:45:

[...] 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 [...]


Dynamik in Formularen : Einfach für Alle on October 21st, 2007 08:35:

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


Acronyms on February 11th, 2008 06:21:

http://docs.jquery.com/Plugins/Validation


George's Blog - Archives for: 2007 on February 13th, 2008 03:12:

[...] 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/ [...]


Vasile (thebookle.com) on October 27th, 2008 13:18:

Awesome, just what I need…


www@www» Blog Archive » JavaScript form validation with jQuery on November 6th, 2008 06:02:

[...] 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 [...]


Leave a Reply

(required)

(required)

Contact

You are more than welcome to contact us if you would like to discuss anything regarding the blog.

About

Front-End Book is run and primarily written by Mattias Hising, an experienced Lead Developer from Uppsala, Sweden. I try to focus my efforts on Front-End related issues, as I find the problems to solve are more complex and interesting than the ones in traditional back-end development.

Twitter | GitHub | FriendFeed | LinkedIn | StumbleUpon | Facebook | Delicious