jQuery

jQuery Form Validation Example

Writing forms is a very common task while developing web applications. But if you need a form you should validate it. Very often it comes to server-side validation, but not necessarily every time. And here jQuery provides a very useful API for rapid creation of client-side form validation. Let’s take a closer look.
 
 
 
 
 
 
 
 

1. HTML

We’ll assume that we need a simple register form (well, not the simpliest possible one, but that’s for this example’s sake)

In head section we’ll download jQuery and jQuery validate libraries to handle form validation. And also Bootstrap to prettify our page quickly.

The form will contain login, email and password fields wrapped in div to make it look better using Bootstrap.

<!DOCTYPE HTML>
<html>
<head>
  <title>JQuery form validation example</title>
  <!-- Download the latest minified version of jQuery -->
  <script src="https://www.webcodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9jb2RlLmpxdWVyeS5jb20vjquery-2.1.4.min.js"></script>
  <!-- Download the latest jquery.validate minfied version -->
  <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
  <!-- Download the latest minified bootstrap version -->
  <link rel="stylesheet" href="https://www.webcodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9tYXhjZG4uYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/3.3.5/css/bootstrap.min.css">
  <!-- Adding some custom styles -->
  <link rel="stylesheet" href="style.css">
  <!-- Adding our jQuery code -->
  <script type="text/javascript" src="js.js"></script>
</head>
<body>
  <!-- Form container -->
  <div class="main">
    <h1>Registration</h1>

    <!-- Sample form -->
    <form action="#" id="form">
      <div class="form-group">
        <label for="login">Login</label>
        <input type="text" name="login" class="form-control">
      </div>

      <div class="form-group">
        <label for="email">Email</label>
        <input type="text" name="email" class="form-control">
      </div>

      <div class="form-group">
        <label for="password">Password</label>
        <input type="password" name="password" class="form-control">
      </div>
      
      <div class="form-group">
        <input type="submit" value="Register" class="submit" class="form-control">
      </div>
    </form>

  </div>
</body>
</html>

2. A bit of CSS

Here we’ll add some custom styles to highlight error messages and set the form alignment

#form label.error {
	color: red;
	font-weight: bold;
}
.main {
	width: 600px;
	margin: 0 auto;
}

3. JQuery

And a simple piece of jQuery code to add validators for the form. We want our script to be executed only when DOM is ready so we’ll place the code in jQuery $().ready method. Then we’ll select the form by id using $("#form").

And finally we’ll pass an object to its validate method with rules for every input in the form and corresponding messages to display to a user if the rule is broken. submitHandler replaces the default submit and is executed when the form is actually ready.

// Waiting until DOM is ready
$().ready(function() {
    // Selecting the form and defining validation method
    $("#form").validate({
        // Passing the object with custom rules
        rules : {
            // login - is the name of an input in the form
            login : {
              // Setting login to be required
              required : true
            },
            email : {
                required : true,
                // Setting email pattern for email input
                email : true
            },
            password : {
                required : true,
                // Setting minimum and maximum lengths of a password
                minlength : 5,
                maxlength : 8
            }
        },
        // Setting error messages for the fields
        messages: {
            login: "Enter you login",
            password: {
                required: "Enter your password",
                minlength: "Minimum password length is 5",
                maxlength: "Maximum password length is 8"
            },
            email: "Enter you email"
        },
        // Setting submit handler for the form
        submitHandler: function(form) {
            form.submit();
        }
    });
});

And this is it! Note that error messages are changed dynamically after user input is changed.

On your screen you should see something like this:

withWatermark

4. Download

Download
You can download the full source code of this example here: JQueryFormValidation

Dmitry Mishchenko

This year I graduate from Applied Mathematics department of Brest State University. I'm fond of genetic algorithms and my degree work will be about generating timetables. Also I'm keen on programming and web-development, especially Java and Javascript. Now I work as a Java Developer at Java department of VRP Consulting.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button