jQuery Simple Validation


Validation in registration forms is extremely important in our web development, we need to learn jquery for validating the form such as online registration forms, contact form html or any web form design in our site for preventing human errors, malicious value’s and make valid value before inserting in the database. In reality validating forms is very easy, there have many jQuery third party plugin out there and ready to use.

But if you wonder on how validate forms your own hand, in this jquery example I would like to share our simple form validation in registration form using jQuery library.

In this tutorial we will create a simple form validation using jquery that have most use input fields, like in real world online registration forms and also we create the dynamic date using php loop and after fill in up the form jQuery will validate the valid values after the value is valid it will pass to php file, so let’s begin.

View Demo | Download Source

1. Creating the Page Template

index.php

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery Simple Validation in Registration Form</title>
<link href="style/style.css" rel="stylesheet" type="text/css" media="all" />
<script type="text/javascript" src="js/jquery-1.9.1.js"> </script>
<script type="text/javascript" src="js/script.js"></script>
</head>

<body>
	<div id="wrap"> <!--wrap start-->
    	<div id="wrap2">  <!--wrap2 start-->

       	<h2 class="free_account">Create an free account</h2>

    	<form action="process.php" method="post" id="register_form">

                <p class="validate_msg">Please fix the errors below!</p>

                <p> <label for="name">First Name</label> <input name="fname" type="text" /> <span class="val_fname"></span> </p>
                <p> <label for="lname">Last Name</label>  <input name="lname" type="text" />  <span class="val_lname"></span> </p>
                <p> <label for="email">Your Email</label> <input name="email" type="text" /> <span class="val_email"></span> </p>
                <p> <label for="password">Password</label>  <input name="password" type="password" /> <span class="val_pass"></span> </p>
                <p> <label for="repassword">Retype Password</label>  <input name="repassword" type="password" /> <span class="val_pass2"></span> </p>
                <p> <label for="phone">Phone No.</label> <input name="phone" type="text" /> <span class="val_phone"></span> </p>
                <p> <label for="birth">Birth Date</label>
                            	<select name="month">
                    				<option value="">Month</option>
                                    <?php
										$months = array('1' => 'Jan', '2' => 'Feb', '3' => 'Mar', '4' => 'Apr', '5' => 'May', '6' => 'June', '7' => 'July ', '8' => 'Aug', '9' => 'Sept', '10' => 'Oct', '11' => 'Nov', '12' => 'Dec');
										foreach($months as $m => $month) {
									?>
                                    <option value="<?php echo $m; ?>"><?php echo $month; ?></option>
                                    <?php } ?>
                                </select>
                                <select name="day">
                    				<option value="">Day</option>
                                    <?php for($day = 1; $day < 32; $day++) { ?>
                                    <option value="<?php echo $day; ?>"><?php echo $day; ?></option>
                                    <?php } ?>
                                </select>
                                <select name="year">
                    				<option value="">Year</option>
                                    <?php
										$year = date("Y");
										for($j = $year; $j > 1949; $j--) {
									?>
                                    <option value="<?php echo $j; ?>"><?php echo $j; ?></option>
                                    <?php } ?>
                                </select>
                <span class="val_bday"></span> </p>
                <p> <label for="gender">Gender</label>  <input name="gender" type="radio" value="m" /> Male <input name="gender" type="radio" value="f" /> Female <span class="val_gen"></span> </p>
            <input type="submit" name="submit" value="Register">
        </form>

        </div>  <!--wrap2 end-->
    </div>  <!--wrap start-->
</body>
</html>

In the index.php file we used the most common input field in web such as input fields, drop down and radio buttons. In the birthday field we turn it into the dynamic loop, for the month we use foreach loop to generate dynamic months and the days we loop 1-32 and the year we decrement the year 1949.

2. The stylesheet

style.css

body {
	font-family: sans-serif;
	font-size:13px;
	background:#CCCCCC;
	color:#444444;
}
p {
	padding:2px
}
#wrap {
	width:820px;
	padding:20px;
	margin:20px auto;
	background:#fff;
	border:1px solid #cc;
	-moz-border-radius:10px;
	-webkit-border-radius:10px;
}
div#wrap2 {
    border: 1px solid #CCCCCC;
    margin-bottom: 10px;
    padding:15px;
}
h2.free_account {
    color: #3399FF;
    display: block;
    margin-bottom: 25px;
}
form#register_form label {
	display:inline-block; /* with block na */
	width:125px;
	font-weight:bold;
}
form#register_form label:after {
	content:":"
}
form#register_form input[type='text'], input[type='password'] {
	display:inline-block; /* with block na */
	width:200px;
	border:1px solid #ccc;
	margin:0;
	padding:5px;
}
form#register_form select {
    border: 1px solid #CCCCCC;
    display: inline-block;
    margin: 0;
    padding: 5px 0;
    width: 68px;
}
form#register_form input[name='submit'] {
	border:1px solid #3399FF;
	background:#3399FF;
	border-radius: 5px;
	margin:10px;
	color:#FFF;
	padding:5px;
	font-weight:bold
}
form#register_form input[name='submit'] {
	cursor:pointer;
}
p.validate_msg {
    border: 1px solid #FF0000;
    font-weight: bold;
    padding: 10px;
	display:none;
	margin-bottom:25px
}
span.validate  {
	color:#F00;
	padding-left:8px;
	font-style:italic;
}

Our simple style

3. The jQuery script

script.js

jQuery(function($) {
	var validation_holder;

	$("form#register_form input[name='submit']").click(function() {

	var validation_holder = 0;

		var fname 			= $("form#register_form input[name='fname']").val();
		var lname 			= $("form#register_form input[name='lname']").val();
		var email 			= $("form#register_form input[name='email']").val();
             var email_regex     = /^[\w%_\-.\d]+@[\w.\-]+.[A-Za-z]{2,6}$/; // reg ex email check
		var password 		= $("form#register_form input[name='password']").val();
		var repassword 		= $("form#register_form input[name='repassword']").val();
		var phone 			= $("form#register_form input[name='phone']").val();
		var phone_regex		= /^[0-9]{4,20}$/; // reg ex phone check
		var month 			= $("form#register_form select[name='month']").val(); // month
		var day 			= $("form#register_form select[name='day']").val(); // day
		var year 			= $("form#register_form select[name='year']").val(); // year
		var gender 			= $("form#register_form input[name='gender']");

		/* validation start */
		if(fname == "") {
			$("span.val_fname").html("This field is required.").addClass('validate');
			validation_holder = 1;
		} else {
			$("span.val_fname").html("");
			}
		if(lname == "") {
			$("span.val_lname").html("This field is required.").addClass('validate');
			validation_holder = 1;
		} else {
			$("span.val_lname").html("");
			}
		if(email == "") {
			$("span.val_email").html("This field is required.").addClass('validate');
			validation_holder = 1;
		} else {
			if(!email_regex.test(email)){ // if invalid email
				$("span.val_email").html("Invalid Email!").addClass('validate');
				validation_holder = 1;
			} else {
				$("span.val_email").html("");
			}
		}
		if(password == "") {
			$("span.val_pass").html("This field is required.").addClass('validate');
			validation_holder = 1;
		} else {
				$("span.val_pass").html("");
			}
		if(repassword == "") {
			$("span.val_pass2").html("This field is required.").addClass('validate');
			validation_holder = 1;
		} else {
			if(password != repassword) {
				$("span.val_pass2").html("Password does not match!").addClass('validate');
				validation_holder = 1;
			} else {
				$("span.val_pass2").html("");
			}
		}
		if(phone == "") {
			$("span.val_phone").html("This field is required.").addClass('validate');
			validation_holder = 1;
		} else {
			if(!phone_regex.test(phone)){ // if invalid phone
				$("span.val_phone").html("Invalid Phone Number!").addClass('validate');
				validation_holder = 1;

			} else {
				$("span.val_phone").html("");
			}
		}
		if((month == "") || (day == "") || (year == "")) {
			$("span.val_bday").html("This field is required.").addClass('validate');
			validation_holder = 1;
		} else {
				$("span.val_bday").html("");
			}

		if(gender.is(':checked') == false) {
			$("span.val_gen").html("This field is required.").addClass('validate');
			validation_holder = 1;
		} else {
				$("span.val_gen").html("");
			}
		if(validation_holder == 1) { // if have a field is blank, return false
			$("p.validate_msg").slideDown("fast");
			return false;
		}  validation_holder = 0; // else return true
		/* validation end */
	}); // click end

}); // jQuery End

In the script.js file, we set variable validation_holder with default value 0, these control the validating values, in the line 8-19 we getting the value in the fields as we validate email via Regular Expression. The validation process start in line 22, so the common logic is if the value is equal to blank the validation_holder set to 1 and return false else return true the validation_holder set to 0.

4. Process Data

process.php

<?php
// author: http://istockphp.com
$fname 		= trim($_POST['fname']); // trim remove white space
$lname 		= trim($_POST['lname']);
$email 		= trim($_POST['email']);
$password 	= trim($_POST['password']);
$phone 		= trim($_POST['phone']);
$birth 		= $_POST['year'].'-'.$_POST['month'].'-'.$_POST['day'];
$gender 	= $_POST['gender'];
// do something. mysql_query
//header("Location: index.php");
//exit();
?>

This process.php file getting the values of the form after they validated, so we use the trim function to remove while space if any, then you can do mysql insert and after inserted the data, redirect to the success page.

5. Done

Were done, we create another jquery sample the Simple Online registration form validation using jQuery. Let’s have a look at what we’ve achieved:

  • Validating the form without third party plugin.
  • We create the dynamic date loop in the field.
  • Simple and working jQuery validation.

If you enjoyed this article, please consider sharing it!

About Axl Mulat

Im Axl Mulat, WordPress and Magento Developer. I create in site (istockphp.com) to share what i learn in my web projects. Add me in Facebook, and , Linkedin.

  • http://www.oshopindia.com Manthan

    This is nice one but we need some attractive one for our website Oshopindia.com. Can this be used in any attractive form?

    Thanks
    Manthan
    Oshopindia.com

    • http://istockphp.com admin

      yeh, you can use any form, just change the ID’s in the code :)

  • alex

    Thanks for the script but we are not able to validate textarea tag can you help?

  • sagar

    i also want submit this form with jquery plzz help me..

  • maheshi

    hi in this jquery i delete phone no validation but after deleting validation it still work what i do for that and i also delete html phone text field and how i slove this please help me!!!

    • axlmulat

      1. remove this code in script.js, line 65 – 76

      if(phone == “”) {
      $(“span.val_phone”).html(“This field is required.”).addClass(‘validate’);
      validation_holder = 1;
      } else {
      if(!phone_regex.test(phone)){ // if invalid phone
      $(“span.val_phone”).html(“Invalid Phone Number!”).addClass(‘validate’);
      validation_holder = 1;

      } else {
      $(“span.val_phone”).html(“”);
      }
      }

      2. remove this in index.php

      Phone No.

      got it?

      • maheshi

        Yes thankx axlmulat

  • Timi Shock-value Oduntan

    This form is not submitting, any help??

    • axlmulat

      hi, the form is submitted if fill all the fields, and the values catch in the ‘process.php’

      you can add the mysql insert on ‘process.php’, got it?

  • unknown

    Hi,

    I have gone through the JQuery simple validation process in your site. It works fine and implemation is good. But I want to suggest you to do a small change with in the validation.

    i.e,

    In Birth Date field,
    When I have selected Feb 31,some year and then submitted the form it is redirecting to success page.
    As we all know the basic thing that February doesn’t contains 31 days. so it has to show an error during the submission.

    Please correct it.

    Thanks.

  • axlmulat

    hi thiru, sorry very late response. by here you request. hopefully you use it..

    https://www.dropbox.com/s/bgyvjg5bcqisj0a/thiru-jquery-simple-validation.zip

  • PanosThanos

    Hi. Thanks for the Tutorial…
    I have a problem with phone validation.
    In this validation someone can input 4 to 20 numbers. I want to change it and make it validate numbers with 10 digits that start with 2.

    I believe that all i have to do is to change the phone_regex in script.js but it doesn’t work !!!

    • axlmulat

      hi Panos,

      just replace this regex, home this help, please like our fan pages…

      var phone_regex = /^[0-9]{2,10}$/;

  • axlmulat

    hey it work, the user can allow to input 2 to 10 digits only in phone field :p

    https://www.dropbox.com/s/1jdlrltsc71nrns/nedhu-jquery-simple-validation.zip