Your question is not very specific but for a recent project, I did something like this:
function validate_form(form){
valid = true;
error = "";
with(form){
error = validateName(first_name);
if(error!=""){
$("#fn_error").html(error);
valid=false;
}else{
// clear error
$("#fn_error").html("");
}
error = validateName(last_name);
if(error!=""){
//last_name.focus();
$("#ln_error").html(error);
valid=false;
}else{
// clear error
$("#ln_error").html("");
}
error = validateEmail(email);
if (error!=""){
$("#email_error").html(error);
//email.focus();
valid=false;
}else{
// clear error
$("#email_error").html("");
}
}
return valid;
}
function trim(s){
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(fld){
var error="";
var tfld = trim(fld.value); // value of field with whitespace trimmed off
var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (fld.value == "") {
fld.style.background = '#FFCCCC';
//error = "You didn't enter an email address.\n";
error = "This field is required.";
} else if (!emailFilter.test(tfld)) { //test email for illegal characters
fld.style.background = '#FFCCCC';
error = "Invalid Email address.";
} else if (fld.value.match(illegalChars)) {
fld.style.background = '#FFCCCC';
error = "Email contains illegal characters.\n";
} else {
fld.style.background = 'White';
}
return error;
}
// field_name should be "first name" or "last name"
function validateName(fld){
var error="";
var tfld = trim(fld.value); // value of field with whitespace trimmed off
if (fld.value == "") {
fld.style.background = '#FFCCCC';
error = "This field is required.";
}else {
fld.style.background = 'White';
}
return error;
}
Instead of setting and clearing the error, you could build the error string if the error exists. And then set and clear only one error depending if an error exists. Follow me?
UPDATE
To separate the errors by commas you would build the error string as mentioned above:
error = "oops you forgot to fill in ";
bad_fields = [];
if (form[name] == ""){
bad_fields.push("name");
}
if (form[email] == ""){
bad_fields.push("email");
}
error_string = error + bad_fields.join(",");
$("#error_div").html("<span class='error'>"+error_string+"</span>");
This is mainly pseudocode, but you get the idea.