I\'m making a form validation, where all fields should be required and also check if the user \"accept terms\", and also check if the e-mail is correct. It almost works, this co
why wont you use a validator plugin.
i use http://jqueryvalidation.org/
Hi this code will work without errors , but i am not sure about your logic is correct.
$("form").submit(function (e) {
e.preventDefault(); // This will prevent the form submission
var response = "";
$('#submit-holder').find('input').each(function(){
if ($(this).val() == '') {
response += ", " + $('label[for="' + this.id + '"]').html();
empty_fields = true;
}
else if ($(this).val() != '') {
empty_fields = false;
$('.alert').hide();
}
else if(empty_fields = true ) {
$('.alert').addClass('alert-danger');
$('.alert').fadeIn();
$('.error_message').text(response.replace(", ", "You need to fill out: "));
message = response.replace(", ", "You need to fill out: ");
response_message(message);
}
else if ($('[name="txtEmail"]').length !== 0) {
var email = $('[name="txtEmail"]').val();
if(IsEmail(email)==false){
message = "The e-mail address you've entered is invalid";
response_message(message);
//return false;
}
}
else if($('#user_terms').not(":checked")){
message = "You need to accept the terms and conditions to continue";
response_message(message);
//return false;
}
});
if($('#user_terms').is(":checked") && !response) {
// Send the form
}
// Functions:
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!regex.test(email)) {
return false;
}else{
return true;
}
}
function response_message(message) {
$('.alert').addClass('alert-danger');
$('.alert').fadeIn();
$('.error_message').text(message);
}