Hi Guys,
I'm doing some simple client side validation with jQuery.
var passedValidation = new Boolean(true);
// Required Field Validators.
if ($('#fbsignup input.firstName').val().trim() == '') {
$('#fbsignup tr.firstName em').show();
passedValidation = false;
}
if ($('#fbsignup input.lastName').val().trim() == '') {
$('#fbsignup tr.lastName em').show();
passedValidation = false;
}
if ($('#fbsignup input.email').val().trim() == '') {
$('#fbsignup tr.email em').show();
passedValidation = false;
}
if ($('#fbsignup input.password').val().trim() == '') {
$('#fbsignup tr.password em').show();
passedValidation = false;
}
if ($('#fbsignup input.screenName').val().trim() == '') {
$('#fbsignup tr.screenName em').show();
passedValidation = false;
}
if (passedValidation == true) {
// All validation passed. Hide the modal signup dialog and post back to signup user.
$('#fbcSignupModal').jqmHide();
return true;
} else {
return false;
}
Essentially, i want to ensure all fields are filled in. If any aren't, return false, else return true. Simple.
Can this be refactored to a single line? (perhaps by applying a class to all elements?).
A caveat on the answer, i do NOT want to use the jquery-validate plugin. I know its awesome, but this is not very difficult validation and i do not want to affect the rest of the form (this is a modal popup).
So, that being said - any ideas?
EDIT
Just to clarify, i do need to know which field wan't filled in, so i can show an * next to it.
EDIT2
Updated the original code to indicate i need to show a required field label and return false if validation fails.
EDIT3
Okay i've rethought my solution, and it looks like i'll need to do a server-call to validate the email against the membership schema. So i'm probably going to end up either wrapping the fields in an update panel or doing a web service post (and return errors in a json array). However, i'll leave this question open for a while and pick the answer with the most votes.
ANSWER
So i've gone with a modified version of @box9's answer. I'll still need to do an AJAX call to the server to validate the email (as my edit above suggests), but this will ensure i only do that if all fields are filled in.
$('#fbsignup input.required').each(function (index) {
if ($(this).val().trim() == '') {
$(this).next('em').show();
passedValidation = false;
}
});
I have an em element directly after the input fields which are required, so i can easily use the .next([selector])
jQuery selector.
Nice and easy.
Thanks for all the answers.