2015-02-05 87 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)//然後做一些邏輯)來評估所述布爾值並在你的代碼塊中寫入你的邏輯。