Wednesday, March 23, 2011

Client-side Form Validation using jQuery Mobile

Lately, I've been involved in a project which is mainly targeting mobile browsers. The decided to use kinda "new" jQuery mobile "library". jQuery Mobile is a ……built over jquery, css, js, multiple browser support, etc…… It's still in beta? Yet, it renders pretty fine, and we didn't have more than a couple of issues with it. But it save us loads of time rendering on a nice range of supported mobile browsers.

For eg, I stepped into a problem with client-side validation lately. When jQuery Mobile renders input of type submit (i.e. a submit button for a form), it actually hides the "input" tag, and replace it with an anchor? (ie "a" tag).

Say, you want to add function to handle "onclick" event, validate the form, before hitting the server-side, and prevent it from submitting if it failed; something like:

<input type="submit" onclick="return ValidateForm()" />

The  function is actually never called because the actual input tag is as jQuery Mobile hides and replaces it by an anchor.

Adding the validation function via js/jquery after the document is ready to the anchor, will allow you to call it on clicking the anchor. Yet, it won't stop the form being submitted.

A nice alternative, is to use an input tag of type button, that is:

 <input type="button" onclick="ValidateForm();" />

And submit the form inside the function handling "onclick", rather than returning true/false, like:

   1:  function ValidateOwnerId() {                
   2:      if (/*form is valid*/) {
   3:          $('#myForm').submit(); // Submit from
   4:      }
   5:      else//not valid
   6:      {
   7:          /*show some error message without submitting form*/
   8:      }
   9:  }

No comments:

Disclaimer

All the opinions expressed on this blog are my own and don't necessarily represent my employer's positions, strategies or opinions.