permalink

24

How To Add Form Validation using jQuery in 2 Easy Steps

valss

 

 

Sometimes you may find yourself working on projects that require some intelligent form field validation..but what’s the easiest way to achieve this? I’ve used everything from the popular Validate plugin to Spry components, but I found all of them a little too much to achieve something so simple. In this post I’m going to show you how to add sleek form validation to your input fields in just two easy steps.

 Update: I strongly recommend checking out more up to date jQuery Validation techniques as this plugin is currently over a year old.

First you’ll need to download the tutorial pack for this post. It’s composed of a small jQuery Plugin I was passed on by a colleague which we’ll be using for this tutorial. To get started lets include both jQuery and the plugin:

 

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="validation.js"></script>

 

Lets take a look at the HTML.

 

HTML >> demo.html

 

To keep things simple our jQuery Plugin uses a template structure for each input field you would like to validate. For this post, I’m going to use the "username" field as an example of how to use it.

 

1. Here is our input field template you can use for anything like usernames, passwords, addresses and so forth. Notice that we have an image area to display a notification icon and a message area to display any validation messages.

 

         <li class="validated" id="FIELDNAME_li">
                  <label for="r_FIELDNAME">Fieldname:</label>
                  <div id="FIELDNAME_img"></div>
                  <input class="validated" name="FIELDNAME" id="FIELDNAME" type="text" maxlength="20" value=""  />
                  <div id="FIELDNAME_msg"></div>
          </li>

Lets now replace FIELDNAME with username to setup an input field that validates.

 

          <li class="validated" id="username_li">
                  <label for="r_username">Username:</label>
                  <div id="username_img"></div>
                  <input class="validated" name="username" id="username" type="text" maxlength="20" value=""  />
                  <div id="username_msg"></div>
          </li>

 

2.  The next stage of setting up a new text field for validation is adding our "username" field to our JavaScript. This takes the form of a check to see if the name of one of the input fields on the page is "username" and if so, what type of validation we would like to apply on it.

JavaScript >> Validator.js

$.fn.validate = {
        init: function(o) {
          //Here’s where I’m checking for my input field name
          if(o.name == ‘username’) { this.username(o) }; 
          if(o.name == ‘password’) { this.password(o) };
          if(o.name == ‘email’) { this.email(o) };
          if(o.name == ‘dob’) { this.dob(o) };
        },
       

//and here’s where I’m definining a validation method for it
//note the regex used to make sure that our username fits the
//expected pattern


        username: function(o) {
          var user = /[(\*\(\)\[\]\+\.\,\/\?\:\;\’\"\`\~\\#\$\%\^\&\<\>)+]/;
           if (!o.value.match(user)) {
             doValidate(o);
            } else {
             doError(o,’no special characters allowed’);
            };
        } 
       

(each of the password, email, date-of-birth items also have their own custom validation scheme which you can see in the tutorial pack)

 

dob

And that’s it!. You can define as many input fields as you would like and validate their content using any type of regular expression that your project requires the data to conform to.

 

If you would like to try the methods described in this post out for your own project, feel free to view the demo here or download the pack here.

24 Comments

  1. Thank you very much!

    it's ok to validate some of the input date in the client/browser side, but it is more important to validate it in the server side.you know it's easy to create a GET/POST request pointing to the cgi or script.

    • Hi David,

      I think that it's just as important to validate what your users enter on the client side as it is on the server side – if you can ensure that the login data being sent back to the server is (or is as close to) what's expected rule-wise then your server can simply get onto the task of adding the new user to the database as opposed to refusing the form back and forth until the user gets it right. Focusing on getting it right on the client side helps to remove a small amount of added communication made to the server (which is why I'm a supporter of developing for both in mind) :)

      • Sorry for commenting on old post — What David was mentioning is that you cannot guarantee the get/post request came from your pages form, and can't be sure that they were even validated with your javascript.

        If you completely rely on server-side scripting to validate your form, that's a serious potential security risk, as that can be bypassed easily.

    • Hi David,

      I think that it's just as important to validate what your users enter on the client side as it is on the server side – if you can ensure that the login data being sent back to the server is (or is as close to) what's expected rule-wise then your server can simply get onto the task of adding the new user to the database as opposed to refusing the form back and forth until the user gets it right. Focusing on getting it right on the client side helps to remove a small amount of added communication made to the server (which is why I'm a supporter of developing for both in mind) :)

  2. I like this but surely you would want to allow some special characters for the password field! some users prefer to use special characters to strengthen their password!

    Then you can trim the field or use escape string on the server side.

  3. Pingback: Tweets that mention How To Add Form Validation using jQuery in 2 Easy Steps | AddyOsmani.com | Where Web Businesses Grow -- Topsy.com

  4. Pingback: Tweets that mention How To Add Form Validation using jQuery in 2 Easy Steps | AddyOsmani.com | Where Web Businesses Grow -- Topsy.com

  5. Thank you very much!

    it's ok to validate some of the input date in the client/browser side, but it is more important to validate it in the server side.you know it's easy to create a GET/POST request pointing to the cgi or script.

  6. Pingback: How To Add Form Validation using jQuery in 2 Easy Steps … Scripts Rss

  7. Pingback: How To Add Form Validation using jQuery in 2 Easy Steps … Scripts Rss

  8. I like this but surely you would want to allow some special characters for the password field! some users prefer to use special characters to strengthen their password!

    Then you can trim the field or use escape string on the server side.

    • Hi Tommy and thanks for the comment. The beauty of this method's Regex support is that you can define a set of Regular expression rules to accept any type of password you would like. For example, if you did want to define a password regex that the field had to validate against you could easily have it report back to the UI prompting the user to include some special characters otherwise their password won't be accepted :)

    • Hi Tommy and thanks for the comment. The beauty of this method's Regex support is that you can define a set of Regular expression rules to accept any type of password you would like. For example, if you did want to define a password regex that the field had to validate against you could easily have it report back to the UI prompting the user to include some special characters otherwise their password won't be accepted :)

  9. how to add validation like you put in your site post a new comment form please provide tutorial and example of this validation using jquery

Leave a Reply

Required fields are marked *.

*