Quick jQuery Form Validation

If you want a quick validation of your form without using any validation plugin, this jQuery snippet could do the trick. This snippet will prevent form submit and change field border color to red, unless user corrects the invalid or empty fields.
JQUERY
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
$(document).ready(function() { $("#my_form").submit(function(e) { //loop through each required field and simply change border color to red for invalid fields $("#my_form input[required=true], #my_form select[required=true], #my_form textarea[required=true]").each(function(){ var proceed = true; $(this).css('border-color',''); //reset border color if(!$.trim($(this).val())){ //if this field is empty $(this).css('border-color','red'); //change border color to red //alert("Field is empty"); 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){ //everything looks good return; //submit form } e.preventDefault(); }); }); });

Usage

Just set your form id to "my_form" and add required attribute to each input field you want to validate, as shown in example below.
HTML
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
<form id="my_form" action="" method="get"> <input type="text" name="name_field" required="true"/> <input type="email" name="email_field" required="true"/> <input type="password" name="password_field" required="true" /> <textarea name="message" required="true"></textarea> <input type="submit" /> </form>
  • THANK YOU VERY MUCH FOR THAT ! I reused it and it works perfectly. I wanted to extend it to validate a phone number INPUT as done for the email regexp but it does not seem to work.
  • Hello sir, thanks for this script but I'ma new in programming , i want to know if i want to validate some few field and leave other example below codes , mobile and email was not mandatory what can do it ?Select status Paid Unpaid Select Chapter Known Unknown Select Gender Male Female Submit
New question is currently disabled!