Simple Form validation jQuery snippet
There are plenty of powerful jQuery validation plugins out there to meet your needs, but sometimes your requirement is so little that you just don’t bother including these plugins into your page, you might just create your own simple validation for your Form. So here’s a simple jQuery validation script you can include in your form page and have almost powerful validation.
Let’s say you have similar HTML form as below, which needs validation.
<form action="" method="post" id="my_form" novalidate>
<label><span>Name : </span><input type="text" name="name" required="true" /></label>
<label><span>Email : </span><input type="email" name="email" required="true" /></label>
<label><span>Message : </span><textarea name="message" required="true" ></textarea></label>
<label><input type="submit" value="Submit Form"></label>
</form>
Here’s simple jQuery validation script, which will loop though each Form field that has required=”true” attribute and validate them. If field is empty or email is incorrect, it will simply change field border color to red, and when user types again the color will change back to normal.
<script type="text/javascript">
$(document).ready( function()
{//simple validation at client's end
$( "#my_form" ).submit(function( event ){ //on form submit
var proceed = true;
//loop through each field and we simply change border color to red for invalid fields
$("#my_form input[required=true], #my_form textarea[required=true]").each(function(){
$(this).css('border-color','');
if(!$.trim($(this).val())){ //if this field is empty
$(this).css('border-color','red'); //change border color to red
proceed = false; //set do not proceed flag
}
//check invalid email
var email_reg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){
$(this).css('border-color','red'); //change border color to red
proceed = false; //set do not proceed flag
}
});
if(proceed){ //if form is valid submit form
return true;
}
event.preventDefault();
});
//reset previously set border colors and hide all message on .keyup()
$("#my_form input[required=true], #my_form textarea[required=true]").keyup(function() {
$(this).css('border-color','');
$("#result").slideUp();
});
});
</script>
Demo
Here’s the demo of simple jQuery validation script.