Basic jQuery Form Validation Example (2mins)

Sam Deering

This tutorial will show you how to setup front-end form validation using jQuery in just a few minutes. I’ve kept this tutorial very basic with simple clear instructions so that anyone can implement some validation on their webpage forms. There is a live demo and also a complete download package at the end of the post.

View Demo Download Code

Example: User Registration Form

register-form1

The Same Form With Validation

This is what your form will look like when a user tries to submit an empty form.
register-form2

Related Posts:

2min Setup Validation Instructions

Step 1 – Include the latest version of the jQuery Library.

Or use the hotlink welcome file:

//hosted by Microsoft Ajax CDN
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>

Step 2 – Download the jQuery Validation Plugin.

Or use the hotlink welcome file:

//hosted by Google API
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Step 3 – Add the following JavaScript validation rules to your webpage (or indlude as seperate js include).

The code below contains the input field validation rules for the form and also includes a direct submit handler (works for mutiple forms on same page).

(function($,W,D)
{
    var JQUERY4U = {};

    JQUERY4U.UTIL =
    {
        setupFormValidation: function()
        {
            //form validation rules
            $("#register-form").validate({
                rules: {
                    firstname: "required",
                    lastname: "required",
                    email: {
                        required: true,
                        email: true
                    },
                    password: {
                        required: true,
                        minlength: 5
                    },
                    agree: "required"
                },
                messages: {
                    firstname: "Please enter your firstname",
                    lastname: "Please enter your lastname",
                    password: {
                        required: "Please provide a password",
                        minlength: "Your password must be at least 5 characters long"
                    },
                    email: "Please enter a valid email address",
                    agree: "Please accept our policy"
                },
                submitHandler: function(form) {
                    form.submit();
                }
            });
        }
    }

    //when the dom has loaded setup form validation rules
    $(D).ready(function($) {
        JQUERY4U.UTIL.setupFormValidation();
    });

})(jQuery, window, document);

Step 4 – Add the HTML for the form and some styles.

The input fields “name” attribute is important as it maps directly to the validation rules.

<!-- HTML form for validation demo -->
<form action="" method="post" id="register-form" novalidate="novalidate">

    <h2>User Registration</h2>

    <div id="form-content">
        <fieldset>

            <div class="fieldgroup">
                <label for="firstname">First Name</label>
                <input type="text" name="firstname"/>
            </div>

            <div class="fieldgroup">
                <label for="lastname">Last Name</label>
                <input type="text" name="lastname"/>
            </div>

            <div class="fieldgroup">
                <label for="email">Email</label>
                <input type="text" name="email"/>
            </div>

            <div class="fieldgroup">
                <label for="password">Password</label>
                <input type="password" name="password"/>
            </div>

            <div class="fieldgroup">
                <p class="right">By clicking register you agree to our <a target="_blank" href="/policy">policy</a>.</p>
                <input type="submit" value="Register" class="submit"/>
            </div>

        </fieldset>
    </div>

        <div class="fieldgroup">
            <p>Already registered? <a href="/login">Sign in</a>.</p>
        </div>
</form>

Here are some optional CSS styles, which I used for the demo.

 /* example styles for validation form demo */
#register-form {
    background: url("form-fieldset.gif") repeat-x scroll left bottom #F8FDEF;
    border: 1px solid #DFDCDC;
    border-radius: 15px 15px 15px 15px;
    display: inline-block;
    margin-bottom: 30px;
    margin-left: 20px;
    margin-top: 10px;
    padding: 25px 50px 10px;
    width: 350px;
}

#register-form .fieldgroup {
    background: url("form-divider.gif") repeat-x scroll left top transparent;
    display: inline-block;
    padding: 8px 10px;
    width: 340px;
}

#register-form .fieldgroup label {
    float: left;
    padding: 15px 0 0;
    text-align: right;
    width: 110px;
}

#register-form .fieldgroup input, #register-form .fieldgroup textarea, #register-form .fieldgroup select {
    float: right;
    margin: 10px 0;
    height: 25px;
}

#register-form .submit {
    padding: 10px;
    width: 220px;
    height: 40px !important;
}

#register-form .fieldgroup label.error {
    color: #FB3A3A;
    display: inline-block;
    margin: 4px 0 5px 125px;
    padding: 0;
    text-align: left;
    width: 220px;
}

That’s it your done!

Next step is to learn how to use Ajax to load custom validation rules.

View Live Demo | Download Source Code Package

Take your jQuery skills to the next level with SitePoint’s premium subscription service. You’ll find dozens of books and courses on JavaScript and jQuery — and more added every month!

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • stu

    DOH! the wordpress is not using the jQuery form validation on this comment form LOL.

    I don’t like how I have to separate the error messages from the rules messages. Seem like another risk of something getting screwed up when markup changes.

    • jquery4u

      @stu – nice spot! :) The messages are optional, if you leave them blank the default messages appear. You can also specify custom validation rules which have the message just after the rule like so:

      //custom validation rule – text only
      $.validator.addMethod(“textOnly”, function(value, element)
      {
      return !/[0-9]*/.test(value);
      },
      “Alpha Characters Only.”
      );

  • WIll

    HI I like your tutorial, very easy to follow.

    I have come across a problem with using the input name=”email”

    I am using a cms which outputs the form code for me and the input name has to be name=”EmailAddress”

    How can I use this without having to change the name=”EmailAddress” in my form?

    I have attempted changing the email: in the suppied JS code to EmailAddress:
    but it did not work.

    Any ideas?

    Thanks

    • jquery4u

      Hi Will, in the code above change “email” to “EmailAddress” on lines 14, 31 and the script below it on lines 20, 21. That should do the trick.
      Sam

  • Muthusamy8931

    Hi, This is a great tutorial to follow.
    I want to know how to do the US phone number validation.

    Is there any option available in your library ?

    Thanks

    • mabuuu

      kl.lkklk.kl.;kl;kl.kl

  • Daniel

    Hi, Is there any option available to type characters only?
    Thanks

  • Pingback: jQuery Ajax Validation Use the Remote Rule | jQuery4u

  • Pingback: 6 jQuery Form Wizard Plugins | jQuery4u

  • Rob

    Is there a way to manually validate the form, without having to submit it? Thanks in advance.

  • Matt

    Good tutorial! Is there any way to send the validated info to a server? My code seems to ignore my $.ajax() function when I add your plugin.

  • Nidhi

    Very good example..thanks

  • SweeHow

    Hi, i have 2 textbox which is password and retype password.
    I want to make sure both are the same using your jquery.
    I used, but it dosen’t compare properly with my password.
    retypePassword: { required: true, equalTo: “#password” },

    • http://jquery4u.com/ jQuery4u

      Hi, sweehow :)

      That code you posted should work. However there is another option to create a custom validation rule:

      $.validator.addMethod(“password_match”, function(value, element) {
      return $(‘#password’).val() != $(‘#retypePassword’).val()
      }, “* your passwords do not match.”);rules : {
      retypePassword : {
      password_match: true
      }
      },

  • Sikh

    Hi. I’ve got a little dilemma. I’m trying to use this kind of validation with GoogleForms as a backend, where in form looks like (for example) “entry.0.single” instead of “firstname” in js above (line 12), which causes “javascript unexpected identifier” in Chrome console. The thing is that I cannot change names, as they are used by backend. Do you have any suggestions how to get around that?

    • http://jquery4u.com/ jQuery4u

      Hi Sikh,

      Not faced this problem myself, in theory you should be able to use “entry.0.single” instead of “firstname” specified in the validation rules (plugin).

  • Melting Dog

    Excellent! Thanks

    • http://jquery4u.com/ jQuery4u

      Thanks guys

  • http://profiles.google.com/gmilby Greg Milby

    hi, just curious why these were init’d “(function($,W,D) {”
    the d is only used – the rest area already in the jq wrapper natively. the w is left flapping out in the wind or was it? o.0
    thanks!

    • http://jquery4u.com/ jQuery4u

      Hi Greg,

      Passing through references to commonly used objects can yield great results when minifying your code such as the global window object can be simply named W… etc As far as I know there is no other advantage of this.

      As for the example above just a bad habit of declaring all I suppose to optimise probably should only include those that are needed.

      Sam

  • Pingback: 6 jQuery Form Input Style Plugins | jQuery4u

  • Brandtley

    Dig the tut… for some wierd reason my validation isn’t firing… think it’s a strange jQuery issue… btw, the hotlink references you mention are swapped :P Got the jQuery Google libs under the Validation instruction and the Valdiation plugin CDN under the jQuery instruction

    • http://jquery4u.com/ jQuery4u

      Hi Brandtley, have you solved this issue?

  • Sepudin

    where should i put the redirect to another page when all validation is pass?btw thanks for script..

    • http://jquery4u.com/ jQuery4u

      Hi Sepudin,
      after I’ve finished the design for the new site, i’ll be writing a few more articles on form validation. A few different aspects and ways of doing it easily.
      Put your redirect code in the submitHandler() function. I would suggest to comment out the form.submit() line and replace it with an ajax request to your back end.
      submitHandler: function(form) { form.submit(); }
      Thanks,
      Sam

  • deepna

    validation error is not coming up in red color – its the normal black color in my form, how to fix this ?

    • http://jquery4u.com/ jQuery4u

      Hi Deepna,
      Have you got a link to your page? It might be that you forgot to include the CSS for the error class should be:

      .error {
      color: red;
      }

  • havocpulse

    Grt tutorial. bt how to validate a select box? I’m looking to validate whether or not a user selects an option..

  • JustMyName

    Thanks for the script..

    i have a question about the rule section…why when i put the “notEqualTo” in rule section its like an error but nothing alert me or something..i dont know is a broblem..please tell me the truth about rule…i have searching in google before i leave a comment in here..

    thanks..

    • phpscripts4u

      I’m getting a lot of requests to do more tutorials on jQuery validation so stay tuned for those soon. In the meantime you could create a custom function to handle the comparison validation. http://jsfiddle.net/trWA2/
      Sam

  • Chris

    Thanks for the tutorial! I’m having a slight problem, though. When I start typing in the input boxes, the error message shows up while I’m typing. Like it starts to validate immediately instead of ‘onblur’. How can I fix this?

    • http://jquery4u.com/ jQuery4u

      You need to add this onfocusout: function(element) { $(element).valid(); } http://jsfiddle.net/R7zbu/
      Thanks, Sam

  • govind

    It’s Not working with Select Box

    • http://jquery4u.com/ jQuery4u

      Hi govind, I’m working on more demos for validation as I’m getting a lot of requests for it. Coming soon.
      Sam

  • govind

    If it’s working Then any one give explanation

  • george

    i tried it but is not working for me :( can anyone help me?

    • http://jquery4u.com/ jQuery4u

      Hi George, yes I’ll help you, can you post some code or show us where your project is?
      Sam

  • simhadri

    very good example………

  • mital

    if i am using REGEX then i am geting some problem . Please give me demo of validation form for using REGEX.
    thanks…..

  • amol

    how to use validation using input id not a name.. is it possible then how?

  • hariharan

    how to validate input when i use tag-name in array ex:

  • hariharan

    how to validate contact no

  • Satyawan chinchkar

    This is very very good website

  • http://www.facebook.com/bugrabenturk Buğra Bentürk

    is this useable, when you load the form from another jQuery function?

  • http://twitter.com/CottonHen Francesco Pensabene

    Hi there! Thanks for the tutorial! I just wanted to ask what is that form (function($,W,D){…code here..})(jquery, window, document); that you used and where I can learn more about it! Thanks

  • radha

    Hai all..If am using mobile field in the above form then how i validate mobile field in the same way as email field validation….

    please help me…………..

  • rajesh s

    (function($,W,D)
    {
    var JQUERY4U = {};

    JQUERY4U.UTIL =
    {
    setupFormValidation: function()
    {
    above these codes i didnt understand their validations in jquery , then please anyone help me

  • Manoj Kumar R K

    The jquery and validate pluign links are switched. Please fix them.

  • yos

    thanks amillion this very good but how can validate the in put to be only number and can i validate phone number using this plugin thanks alot.

  • kajal

    hi how to add default value in input fields?

    • Alex
  • atif

    Just say……Nice

  • atif

    I think,it will be helpful for me.thanks

  • govind

    phone:{
    number: true,
    minlength:10
    }, number not work

  • govind

    how to work for first name alpha only

  • Kathy

    Very nice, thank you. I have two problems – first, the first field and its label are inset by about 15 pixels. The second is that I cannot get your background to even load in FF. I look in Firebug and it does not show it loading even though I clearly specific it in the css. Any ideas?

    • robin hud

      make sure your css internal ,external css may cause problem to access.

  • http://sauhi.com/ Lại Đình Cường

    Sorry, but I want to know what is plugin highlight code which you are using?

  • paparts

    The tutorial is very nice but your method is overkill especially for beginners.

  • Sanjeet Mani Tripathi

    Hi, This is a great tutorial to follow.
    I want to know how to do the US phone number validation.

  • Vishakha

    I want to show a loading message as soon as the validator function is called. How to do that?

  • chadfetter

    Followed all of the instructions in the tutorial, was excited to see the results, but instead all of the function code is displaying on the screen. Why?

  • siddhu

    well !! this is a nice tutorial but there is an disadvantage !! when click on register button with empty fields the page is disturbing!!! and the jquery or script whatever used is working fine .. good for beginners.. any one of you detect the disadvantage which i said..??

  • Jeremy Steal

    I am the begginer, so this syntax is killing me.