Monday, February 07, 2011

jQuery Mobile Form Validation

Note: I've updated the following post to work with jQuery Mobile 1.0+. After the beta version they deprecated the Orientation Classes that this post originally used to handle the layout of the error messages. jQuery Mobile recommends using CSS3 Media Queries instead. If you need support for older browsers then respond.js is a nice polyfill for this.

I am working on a jQuery Mobile application and one of the standard requirements when you have form elements is to provide client-side validation.

I hadn't seen an example of that yet, so my first inclination was to use the jQuery Validation plugin. As it turns out, the implementation is about the same as you would expect with a non-mobile solution.

In this case I just adding metadata validation classes to the input elements to indicate what rules (example: required, email, etc...) need to be checked when the form is submitted. You can provide these rules also programmatically, but I won't focus on that technique in this post. You can find more details about how to provide validation rules at runtime in the plugin's documentation.

In JavaScript, all you have to do is to call the validate() method off of the form element and provide a submitHandler that will perform the action once your form has passed all it's validation rules.

An interesting challenge comes on mobile devices when considering how to display the validation message in portrait versus landscape mode. I wanted the alignment of the errors to show up different depending upon the orientation.

As it turns out, the solution to this problem was a simple matter of changing my CSS. We can use CSS3 Media Queries to style the page depending on the orientation of the mobile device. By using the following CSS the validation errors will display differently depending if the mobile device is in portrait or landscape mode.

The following is an embedded working jsFiddle example using all the above HTML, CSS, JavaScript, and Resources. If you want to play and tweak with the code snippets you can click the "+" to the right of the "Resources" tab.

Since simulating portrait vs landscape mode on a desktop browser is slightly difficult I took some screenshots from my iPhone for you to see the difference.