Validating forms

Validating a form before it is submitted to the server saves bandwidth and time as errors can be trapped at the client side itself. A server request can thus be avoided. In a jQuery Mobile application, forms can be validated using JavaScript. This recipe shows you how to validate the entries made in a Blog Comments Form .

Getting ready

Copy the full code of this recipe from the code/05/validate-form sources folder. This code can be launched using the URL http://localhost:8080/05/validate-form/main.html.

How to do it...

  1. In main.html, add the following code to create a form:
    <form id='commentform' action='#' method='post'>
      <div data-role='fieldcontain'>
        <label for='username'>Name</label>
        <input id='username' name='username' type='text' required placeholder='Enter Name' />
      </div>
      <div data-role='fieldcontain'>
        <label for='email'>Email ID</label>
        <input id='email' name='email' type='email' required placeholder='Enter Email' />
      </div>
      <div data-role='fieldcontain'>
        <label for='comments'>Comments</label>
        <textarea id='comments' name='comments' required placeholder='Enter Comments <10-100 chars long>'></textarea>
      </div>
      <div id='errmsg' style='color: #f00'></div>
      <input id='submitid' type='submit' data-transition='pop' value='Submit Comment'/>
    </form>
  2. Add the following script to validate the comments field:
    $('#main').live('pageinit', function(event) {
      $('#commentform').submit(function() {
        var len = $('#comments').val().length;
        if ( len < 10 || len > 100 ) {
          $('#errmsg').text('Invalid comments. Length must be between 10-100 chars').show().fadeOut(5000);
          return false;
        }
        else
          return true;
      });
    });

How it works...

In main.html, add a form (id='commentform') and add the following three fields to the form, username (type='text'), email (type='email'), and comments (textarea). Add the required attribute to all the three fields to specify them as mandatory. Add appropriate hints to the user by using the placeholder attribute as shown in the previous code. Add an empty div (id='errmsg') to the form to display any error messages on form validation.

When you load the form and click on the Submit Comment button without entering the Name field, the following error message is shown:

How it works...

The following error is shown when you click on the submit button without a valid Email ID:

How it works...

Add the pageinit event handler as shown in the previous script. This will get invoked after the page has been initialized at start-up. Here define the submit() method of the form to validate the length of the comments. If the comment has an invalid length, display the error message for five seconds after which it fades out. Now since there was an error, return false from the submit method; the form will not be submitted.

How it works...

Post successful validation, return true from the submit() method to successfully submit the form to the server.

There's more...

In this recipe, the form's action is set to # or the same URL as the current HTML page. This form is called a self-submitting form . The default response in such cases is the form content itself. If the form was served by a web server, the response to the post can be custom generated. If you are using the nodejs web server that is shipped with the source code of this book, then you will get a custom success response instead of the form contents.

Unique IDs in a form

In a jQuery Mobile application, since multiple pages can reside in the DOM at the same time, you should ensure that the IDs for the form controls are unique. The IDs should be unique across the entire app and not just in a single page. Lookups and form behavior could fail or behave differently if you do not follow this rule. Some browsers might still support duplicate IDs to a certain extent but this is not guaranteed.

See also

  • The Submitting a form using POST recipe
  • The Fetching data using GET recipe
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.162.26