我的表单目前检查两个电子邮件字段以确保它们匹配。我还希望确保两个电子邮件字段都不为空,并且已选中复选框。我一直在寻找例子,似乎没有什么可以做的。
非常感谢任何帮助。
<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>
答案 0 :(得分: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 :(得分:1)
检查两个文本字段是否都有文字:
var regex = /\S+@\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)
)
答案 2 :(得分:0)
如果你使用的是AngularJS,你可以创建一个变量并将其设置为ng-model =“[你的变量在这里]”。
例如,代码可能如下所示:
<input type="checkbox"
ng-model="$scope.emailConfirm"/>
然后,您可以创建一个Javascript控制器来评估模型的布尔值。使用条件(即if($ scope.emailConfirm)//然后执行一些逻辑)来评估所述布尔值并在THAT代码块中编写逻辑。