dsebao
8/12/2015 - 7:11 PM

Simple validation in form with jQuery

Simple validation in form with jQuery

var proceed = true;

$("#contact_form input[required=true], #contact_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 == true){
      //Continue sending the email in ajax
    }
});