我正在进行表单验证,其中应该要求所有字段,并检查用户是否“接受条款”,并检查电子邮件是否正确。它几乎可以工作,如果我没有输入姓名/电子邮件等,这段代码会给我一个回复,但是如果我输入这些信息,它就不会隐藏().alert。然后不响应术语复选框和“有效电子邮件”检查。如果没有“响应”,.alert也应该总是“隐藏”。
此代码在哪里失败?有什么想法吗?
$("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)
}
答案 0 :(得分:0)
为什么不使用验证器插件。
答案 1 :(得分:0)
嗨,这段代码可以正常工作,但我不确定你的逻辑是否正确。
$("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);
}