jq beginner jq beginner - 7 months ago 37
jQuery Question

validate all form elements at once using jquery

i'm validating a form but the validation goes a field by field and i want it to validate all fields at once on submit

here's the js code not inside document ready

function checkUser(){
var userlen = $("#user").val().length;
if(userlen<4){
$("#user").css("background-color","#d2699b");
return false;
}
else{
$("#user").css("background-color","#0C9");
return true;
}
}

function checkEmail(){
var email = $("#email").val();
if((email.length < 6) ||
(email.indexOf('@',0) < 1) ||
(email.lastIndexOf('@') != email.indexOf('@',0)) ||
(email.lastIndexOf('@') > (email.length - 5)) ||
(email.lastIndexOf('.') > (email.length - 3)) ||
(email.lastIndexOf('.') < (email.length - 4)) ||
(email.indexOf('..',0) > -1) ||
(email.indexOf('@.',0) > -1) ||
(email.indexOf('.@',0) > -1) ||
(email.indexOf(',',0) > -1)){
$("#email").css("background-color","#d2699b");
return false;
}
else{
$("#email").css("background-color","#0C9");
return true;
}
}

function checkPhone(){
var phone = $("#phone").val();
if(!$.isNumeric(phone)){
$("#phone").css("background-color","#d2699b");
return false;
}
else{
$("#phone").css("background-color","#0C9");
return true;
}
}

function checkCountry(){
var country = $("#country").val();
if(country == 0){
$("#country").css("background-color","#d2699b");
return false;
}
else{
$("#country").css("background-color","#0C9");
return true;
}
}

function validate(){
if(!checkUser() || !checkEmail() || !checkPhone() || !checkCountry() ){
return false;
}
else{
return true;
}
}


and the html code

<form method="post" action="data.php" onsubmit="return validate();">
<table width="40%" border="1">
<tr>
<td>user</td>
<td><input type="text" id="user" onblur="checkUser()" /></td>
</tr>
<tr>
<td>email</td>
<td><input type="text" id="email" onblur="checkEmail()" /></td>
</tr>
<tr>
<td>phone</td>
<td><input type="text" id="phone" onblur="checkPhone()" /></td>
</tr>
<tr>
<td>country</td>
<td><select id="country" onchange="checkCountry()">
<option value="0">choose</option>
<option value="egypt">egypt</option>
<option value="usa">usa</option>
</select></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" id="save" value="save" /></td>
</tr>
</table>
</form>


code in action : http://jsfiddle.net/JCtyJ/

Answer

Using your code, you could do it like that:

DEMO

function validate(){
    $.each($('form :input'),function(){
        $(this).blur().change();        
    });
    if(!checkUser() || !checkEmail() || !checkPhone() || !checkCountry() ){
        return false;   
    }
    else{
        return true;
    }
}