We have ended up our last session by learning to implement media player in jQuery. Today we will continue jQuery programming session by creating a form validator in it. Form validation is a really an important feature for web security. Almost 99.99% website validate their form before submitting just to prevent any kind of malicious activity. JQuery also can validate web forms in a good way. But jQuery is not a server side language so we cannot retrieve data from database using jQuery. But it works very well from the client side without any load on server.
Let’s start coding:
Head tag metarial:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <script src="https://ajax.microsoft.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js"></script>
Just add these script tags. First code has jQuery library file and the second has the jQuery validate plugin.
jQuery coding:
<script> $(document).ready(function() { $("#form").validate(); }); </script>
In this jQuery coding, validate(); function is a really important part of this article which works with the support of jQuery validate plugin. This function can validate all of our form with some HTML adjustment.
$(“#form”).validate();
And #form is the id to select the form as you can see in the HTML markup.
<form id=”form”> <label for=”fname”>Insert First Name</label> <input class=”required” type=”text” id=”fname”> <label for=”lname”>Insert Last Name</label> <input class=”required” name=”lastName” type=”text” id=”lname” > <label for=”email”>Email</label> <input class=”required email” type=”text” id=”email”> <label for=”pnumber”>Insert phone number</label> <input class=”required” type="text" id=”pnumber”> <label for=”age”>Insert your age</label> <input type=”date” id=”age”> <input class=”button” type=”submit” value=”Get register” /> </form>
Note: When you markup the HTML for validating a form using jQuery validate plugin then you must remember to add a class “required” with every element which you need to validate. For validating in the perfect way, add a class “required email”.
I hope you have enjoyed and learnt in simple way to create a form validator in jQuery. Please let us know your reviews regarding this topic in the comments below and stay tuned for next jQuery session.