By Julian Motz

Basic jQuery Form Validation Example (2mins)

By Julian Motz

This popular article was updated on 18th August, 2016 to correct some minor errors and reflect the current version of the library. Comments pertaining to the old article were deleted.

This tutorial shows you how to set up a basic form validation with jQuery, demonstrated by a registration form.

We’re going to use the jQuery Validation Plugin to validate our form. The basic principle of this plugin is to specify validation rules and error messages for HTML elements in JavaScript.

Here’s a live demo of what we’re going to be building:

See the Pen Basic jQuery Form Validation Example by SitePoint (@SitePoint) on CodePen.

Step 1: Include jQuery

First, we need to include jQuery v1.x as the validation plugin is currently only compatible with jQuery versions lower than 2.0.

There are the following download options:

  • Download it from
  • Download it using Bower: $ bower install jquery#1.x --save-dev
  • Download it using npm: $ npm install jquery@1.x --save-dev
  • Use a CDN:

Create a new HTML file named index.html and include jQuery before the closing </body> tag:

<!-- Change the "src" attribute according to your installation path -->
<script src="vendor/jquery/dist/jquery.min.js"></script>

If you’d like to use Bower or npm but aren’t familiar with them, you might be interested in these two articles:

Step 2: Include the jQuery Validation Plugin

Choose between:

  • Download it from the plugin’s website
  • Download it using Bower: $ bower install jquery-validation
  • Download it using npm: $ npm install jquery-validation
  • Use a CDN:

Include the plugin after jQuery:

<!-- Change the "src" attribute according to your installation path -->
<script src="vendor/jquery-validation/dist/jquery.validate.min.js"></script>

Step 3: Create the HTML Form

For the registration we want to collect the following user information:

  1. First name
  2. Last name
  3. Email
  4. Password

So, let’s create our form containing these input fields:

<div class="container">
  <form action="" name="registration">

    <label for="firstname">First Name</label>
    <input type="text" name="firstname" id="firstname" placeholder="John"/>

    <label for="lastname">Last Name</label>
    <input type="text" name="lastname" id="lastname" placeholder="Doe"/>

    <label for="email">Email</label>
    <input type="email" name="email" id="email" placeholder=""/>

    <label for="password">Password</label>
    <input type="password" name="password" id="password" placeholder="&#9679;&#9679;&#9679;&#9679;&#9679;"/>

    <button type="submit">Register</button>


When integrating this into a real application, don’t forget to fill in the action attribute, to make sure the form is submitted to the correct destination.

Step 4: Create Styles for the Form

Create a new file, css/styles.css, and include it in the <head> section of your HTML file:

<link rel="stylesheet" href="css/style.css"/>

Copy the following styles into the newly created file:

@import url("");

/* Styles */
* {
  margin: 0;
  padding: 0;

body {
  font-family: "Open Sans";
  font-size: 14px;

.container {
  width: 500px;
  margin: 25px auto;

form {
  padding: 20px;
  background: #2c3e50;
  color: #fff;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
  border-radius: 4px;
form label,
form input,
form button {
  border: 0;
  margin-bottom: 3px;
  display: block;
  width: 100%;
form input {
  height: 25px;
  line-height: 25px;
  background: #fff;
  color: #000;
  padding: 0 6px;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
form button {
  height: 30px;
  line-height: 30px;
  background: #e67e22;
  color: #fff;
  margin-top: 10px;
  cursor: pointer;
form .error {
  color: #ff0000;

If you’re using Compass (SCSS) you can alternatively use the following to style the form:

@import "compass";
@import url("");

/* Color settings */
$formBg: #2c3e50;
$formColor: #fff;
$inputBg: #fff;
$inputColor: #000;
$buttonBg: #e67e22;
$buttonColor: #fff;
$errorMsgColor: #ff0000;

/* Styles */
* {
  margin: 0;
  padding: 0;

body {
  font-family: "Open Sans";
  font-size: 14px;

.container {
  width: 500px;
  margin: 25px auto;

form {
  padding: 20px;
  background: $formBg;
  color: $formColor;
  @include border-radius(4px);

  button {
    border: 0;
    margin-bottom: 3px;
    display: block;
    width: 100%;
  input {
    height: 25px;
    line-height: 25px;
    background: $inputBg;
    color: $inputColor;
    padding: 0 6px;
    @include box-sizing(border-box);
  button {
    height: 30px;
    line-height: 30px;
    background: $buttonBg;
    color: $buttonColor;
    margin-top: 10px;
    cursor: pointer;
  .error {
    color: $errorMsgColor;

Note the styles for .error, which will be used for validation error messages.

Step 5: Create the Validation Rules

Finally, we need to initialize the form validation plugin. Create a new file js/form-validation.js and reference it after the <script> tag of the jQuery Validation plugin:

<script src="js/form-validation.js"></script>

Copy the following code into the newly created file:

// Wait for the DOM to be ready
$(function() {
  // Initialize form validation on the registration form.
  // It has the name attribute "registration"
    // Specify validation rules
    rules: {
      // The key name on the left side is the name attribute
      // of an input field. Validation rules are defined
      // on the right side
      firstname: "required",
      lastname: "required",
      email: {
        required: true,
        // Specify that email should be validated
        // by the built-in "email" rule
        email: true
      password: {
        required: true,
        minlength: 5
    // Specify validation error messages
    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"
    // Make sure the form is submitted to the destination defined
    // in the "action" attribute of the form when valid
    submitHandler: function(form) {


That’s it, you’re done! Now you have an idea how to set up form validation with jQuery. Please keep in mind that this doesn’t replace server-side validation. It’s still possible for a malicious user to manipulate or bypass the validation rules (e.g. using the browser’s developer tools).

  • 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?


    • 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.

  • 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 ?


    • mabuuu


  • Daniel

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

  • 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” },

    • 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?

    • 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

  • 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

    • 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.


  • 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

    • 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..

    • 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(); }

  • deepna

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

    • 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..


    • 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.

      • lbfromla

        This is a beautiful overview/introduction. Simple and neat!

  • 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?

  • govind

    It’s Not working with Select Box

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

  • govind

    If it’s working Then any one give explanation

  • george

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

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

  • 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.

  • 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

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

  • 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

    var JQUERY4U = {};

    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

    number: true,
    }, 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.

  • 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?

    • Ahjusshi Otaku

      bit late for this, but did you enter the javascript in the html document without script tags? All of that code under step 5 should be between script tags or in a separate file, which is called using script tags. Google how to embed javascript or how to link to javascript.

  • 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.

  • Joseph Edwards VIII

    Thanks! BTW, it looks like the CNDs are backwards in steps 1 & 2. The first step references the jQuery library, but gives the CDN for the validation plugin, whereas the 2nd step references the validation plugin but gives the CDN for jQuery library. Heh. Just, y’know… FYI.

  • Nitesh Goyal

    Is it possible that I can keep one of these input fields out of the Form and the validation still work?
    If yes then please help me out with the same.

  • Thirumala Reddy

    Hi thanks for Sample form,
    Browsers Auto Complete(Auto suggest) in test field that time jquery form validation not trigger. please update the solution.
    Case:- First enter the all the fields(email like:- )-> click register.
    next enter the all the fields(email like:- t )-> click register-> show’s error message -> then auto suggest the email.

  • Chandra Prakash

    great tutorial

  • Andrea Keane

    Your first ‘View Demo’ link does not work.
    The bottom ‘View Demo’ works.
    Just thought you’d like to know.

  • jalil

    I am also a beginner and I would prefer using some ready code, somewhat like this

  • thiyagarajan

    Superb!!! example easily any one can learn this technique, thanks for share this

  • EhsAn Ashar (SaaNi)

    Fine tutorial, works fine.. i have a query regarding phone number validation? how would we do phone validation using this code? Thanks :)

  • siva (from india)

    Hi very very thanks….

  • siva (from india)

    Hi above coding along with redirect page pls send me

  • siva (from india)

    Hi above coding along with redirect page code pls send me

  • GB

    Excellent tutorial!

  • Pablo Valor

    JQUERY4U ??
    Why that stupid name?

  • Ashish

    What if i have multiple emails ? A comma separated email list, can it validate that ?

  • hackfield boy

    Great Tutorial !

    I think below line is’nt necessary in the validation message section.

    email: “Please enter a valid email address”,

    Since validation jquery by default shows the the exact same message. But still its helpful in case of customise message

  • Nyimax

    I want to validate my form which is dynamically added. How can i do that?. Help me please

  • Shamir Mohammad

    very helpful tutorial. Thanks

  • WassailAnyone?

    This plug in conflicts with my basic ajax script. If is implemented, I get the expected jquery validation, but my ajax does not populate onto the correct html page ( rather a new page is created from the contact.php code). If I remove the plugin , then the ajax works as expected.

    I put my actual form-validation.js into no conflict mode (but that doesn’t help).

    • Please share your “basic ajax script”, so that I can help you

  • Joseph Mtinangi

    Thanks, it is very helpful

  • Bhavana Kumari

    validation is not working for drop down list.could you please help me ..and provide me code.

    • According to your second comment it seems that you’ve answered your problem yourself.

  • Bhavana Kumari

    thanks for this tutorial,and I don’t have any problem with drop down also…thankyou so much

  • Andy Gradel

    Thanks for sharing… this was a breeze.

  • Ale Pandis

    Hi Julian do you know validator.addmethod and the rules to use it?

  • juan

    how to use min and maxlength together??

  • Praveen Kumar

    You sure that the form won’t submit if the validation fails??
    Also where would this custom error messages appear?

    • Yes. You can test everything in the provided fiddle yourself. The error messages appear when you have wrong input values.

  • Aya

    Thanks a lot
    But the validation does not work with jquery 1.5.1

    • You’re right, I’m getting an error from the validation plugin too. As you can see from the plugin’s page, they haven’t tested it with this version:

      jQuery, tested with 1.7.2, 1.8.3, 1.9.1, 1.11.1

      You’ll have to update jQuery.

  • hend e

    i have a question .. the form i made works if two fields are filled not all the required fields..

    • Sorry, I don’t understand this question. Can you please try to describe it in more detail?

      • hend e

        i have three inputs (name ,password and email) all of them are required.
        when i used the validation i tried filling name input and password input and leaving email input empty.. it didn’t show any error message

  • Kadeem Hakeem Best

    Thanks for sharing. Everything works great expect when I try to validate dropdown lists

  • ravkasu

    how to add css styles in that jquery script please make it an example.

    • You can add custom styles to the style.css file

  • Hello!

    Thank You For This Awesome Article. I don’t have idea about validation but after reading your post my mind has cleared about this. By the told method I have insert this on my website and this is also working . I am so thankful to your for publishing this tutorial.

    Thanks For Sharing This Great Article
    Keep Sharing Like This…

    -Humna Yousaf

  • Gunwant Suryawanshi

    After successfully importing form.validation.js and jquery.validate.min.js file still getting error on console:-
    Uncaught TypeError: $(…).validate is not a function(…) anyone having idea what i am missing here?

    • It seems that you haven’t embedded the validation plugin correctly. Please open your developer tools and inspect the loaded files under “network”.

  • Rinchen Dukpa

    Is there a way to restrict only number in a text box?

  • Rinchen Dukpa

    I figured out looking into the library – ‘number: true’

  • Manish Koju

    how to validate unique data?

  • Ashley Benintende

    I have been able to successful use this article to validate my form with an extra radio button selection! But my professor wants us to display the selection of the radio button. Can you help me figure out how to do this?

    • What do you mean with

      selection of the radio button


      • Ashley Benintende

        Say you have two options:
        Would you like to be contacted via phone or email? And with a radio button you select phone, after submitting I need a statement somewhere on the page that says “You chose to be contacted via phone.” + “Thank you for your submission.”

        • Well, that’s not related to the validation itself. You’ll have to check if which radio button was selected, e.g. using this code

          • Ashley Benintende

            OK. Thank you. Can I add that javascript to the existing that we created in this article? When I try to add more code in for a different function, the entire sequence stops working. (I know I am off topic but you are the first person I have found that explains this in a way I can understand)

  • Sparty

    I’m having an issue with radio button validation. I get the intended error message when a user attempts to move forward without making a selection, but unfortunately, it is placed at the start of the radio button options. I see the in the css where the error color is set but I don’t see a corresponding “error location” in the html.

    Tldr version – How do I direct where the error message pops up on a page with radio buttons?

  • kabera global

    very nice explained. I want to set the the mobile number validation to my form. Please help me with the best way

  • Kai

    Hello. Thanks for this. Works great. How would I configure the validation for a group of checkboxes? E.g. If checkbox1, checkbox2 or checkbox3 are not selected, show an error message to ask them to select at least one?

  • Deepesh Thapa

    How do i validate if a file has been uploaded or not ?

  • Deepesh Thapa

    how do I Validate If image has been uploaded or not?

  • Michael Clayton

    when I submit the form, the validation causes the fields to have way too much padding! The input grows from usual size, to like 300px padding. Why is this happening?

  • Francisco Rodriguez

    Thank you. Great article!
    I would like to add a regular expression to validate the password strength, how would I do that in your example?


Get the latest in JavaScript, once a week, for free.