Monday, 11 June 2012

Validating a Registration form with jquery

Files Required    view Demo how it works

1)Register.php
2)jquery-lastest.js which can be downloaded from jquery.com (or)
   <script src="http://code.jquery.com/jquery-latest.js"></script>
3)validate.js - A jquery form validation script (or)
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>

register.php

<head>

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


<!--inluding jquery files in our programs-->


<script src="http://code.jquery.com/jquery-latest.js"></script>

 <script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>

<!--included jquery files--> 


<script>
  $(document).ready(function(){

    $("#form-elements").validate();

  });

  </script>

</head>

<?php

include "db_connect.php";
if(!$_POST['submit']) //if submit hasn't been clicked then keep showing html form
{
?>
<form action="register.php" method="post" id="form-elements">
<ul>
<li>First Name*: <input type="text" name="first" id="projectTitle" class="required"/><br/>
<span class="error"> </span></li>
<li>Last Name*: <input type="text" name="last" class="required"/><br/><span class="error"> </span></li>
</li>
<li>Desired Username*: <input type="text" name="username" class="required"/><br/><span class="error"> </span></li>
<li> Password*: <input type="password" name="password" class="required"/><br/><span class="error"> </span></li>
<li>Confirm Password*: <input type="password" name="pass_conf" class="required"/><br/><span class="error"> </span></li>
<li> Email*: <input type="text" name="email" class="required email"/><br/><span class="error"> </span></li>
<li>About: <textarea name="about" >Tell us about yourself</textarea><br/></li>
<li><input type="submit" name="submit" value="register"/>
&nbsp;&nbsp;or&nbsp; <a href="login.php">Login here</a><br/></li>
<ul>
<?php
}
else
echo 'form submitted';
?>
Explanation:

<script>
  $(document).ready(function(){
    $("#form-elements").validate();
  });
  </script>

we are calling the function validate and sending the form to be validated by sending its id
Consider this line in the above script:
  $("#form-elements").validate();


<form action="register.php" method="post" id="form-elements">


The id="form-elements" has been used to validate function as
$("#form-elemnets").validate();

Now validating the form:

<li>First Name*: <input type="text" name="first" id="projectTitle" class="required"/><br/>
<span class="error"> </span></li>

Notice the class="required"  this makes the input field as required.
Now to Display the error if the user has not entered a value in the Required field then we write <span class="error"></span>    The error will be displayed in this span                                                                                                              

No comments:

Post a Comment

Search Engine Submission - AddMe