2015-02-05 80 views
0

我的表单目前检查两个电子邮件字段以确保它们匹配。我还想确保两个电子邮件字段都不为空,并且复选框已被选中。我一直在搜寻例子,似乎没有什么可以做的。Javascript表单验证(多个条件)

任何帮助将不胜感激。

<form action="" method="post" name="submission" onsubmit="return checkEmail(this);">  
     <label for="email">Email</label>   
     <input id="email" maxlength="55" name="email" type="text" value="<?=htmlspecialchars($_POST["email"]) ?>" /><br/> 
     <label for="emailconfirm">Confirm email address</label>  
     <input id="emailconfirm" maxlength="55" name="emailconfirm" type="text" value="<?=htmlspecialchars($_POST["emailconfirm"]) ?>" /><br/>  
     <label for="checksign">By completing this form, you agree to the terms and conditions above. If you do not agree to these terms, your application will not be considered.</label> 
     <input class="check" id="checksign" name="checksign[]" type="checkbox" value="Yes" /> 
</form> 

<script type="text/javascript" language="JavaScript"> 
function checkEmail(theForm) { 
    if (theForm.email.value != theForm.emailconfirm.value) 
    { 
     alert('E-mail addresses do not match.'); 
     return false; 
    } else { 
     return true; 
    }  
} 
</script> 

回答

1

而不是增加到checkEmail()功能我建议它改变到整个形式的功能。 Example

function validateForm() { 
 
    
 
    var email = document.getElementById('email'); 
 
    var c_email = document.getElementById('emailconfirm'); 
 
    var check = document.getElementById('checksign'); 
 
    var error = ''; 
 
    
 
    if (email.value != c_email.value) { 
 
     error = "The provided emails do not match!"; 
 
     alert(error); 
 
     return false; 
 
    } else if (email.value.length == 0 || c_email.value.length == 0) { 
 
     error = "One of more of the emails provided are empty."; 
 
     alert(error); 
 
     return false; 
 
    } else if (!check.checked) { 
 
     error = "Please accept our terms."; 
 
     alert(error); 
 
     return false; 
 
    } 
 
    
 
}
<form action="" method="post" name="submission" onsubmit="return validateForm();"> 
 
    <!-- controls.. --> 
 
</form

虽然这并工作,它不检查有效的电子邮件,他们不只是把一个或两个空格等在电子邮件输入。这需要检查一些正则表达式的输入。

1

检查两个文本字段中有文字:

var regex = /\[email protected]\S+\.\S+/; 
(typeof theForm.email.value !== 'undefined' && 
typeof theForm.emailconfirm.value !== undefined && 
theForm.email.value.length > 1 && 
theForm.emailconfirm.value.length > 1 && 
regex.test(theForm.email.value) 
) 
0

如果您正在使用AngularJS你可以创建一个变量,将其设置为NG-模型=“[您的变量在这里]”。
例如,代码可能如下所示:

         <input type="checkbox" 
             ng-model="$scope.emailConfirm"/> 

然后,您可以做一个Javascript控制器,将评估一个布尔模型。使用一个条件(即如果($ scope.emailConfirm)//然后做一些逻辑)来评估所述布尔值并在你的代码块中写入你的逻辑。