如果输入字符串包含特定值,请不要提交表单

时间:2017-05-09 15:56:25

标签: javascript jquery jquery-validate

我有一个HTML表单,其中包含一个请求用户电子邮件地址的输入。如果输入了多个电子邮件地址,则不应允许表单提交,例如@ donotsubmit.com,@ donot.submit.com。

使用jQuery,如果输入包含这些字符串,是否可以阻止表单提交?代码如下所示:

<input class="form-control emailrequired" id="Email" name="Email" placeholder="Email" type="text" value="" />
<script type="text/javascript">
$().ready(function () {
    $.validator.addMethod("cRequired", $.validator.methods.required, "Please ensure this field is complete");
    $.validator.addClassRules("emailrequired", { cRequired: true, email: true });
});
</script>

修改

使用jQuery Array更新了脚本。我遇到的问题是jQuery Validate没有使用inArray语句将字段标记为有效/无效。

<input class="form-control emailrequired" id="Email" name="Email" placeholder="Email" type="text" value="" />
<script type="text/javascript">
$().ready(function() {
   $.validator.addMethod("cRequired", $.validator.methods.required, "Please ensure this field is complete");
   $.validator.addMethod("domain", function(value, element) {
       var emailAddress = $('#Email').val();
       var emailDomain = emailAddress.substr(emailAddress.search('@') + 1);
       var invalidAddresses = ["donotsubmit.co.uk"];
       if (jQuery.inArray(emailDomain, invalidAddresses) !== -1) {
           event.preventDefault();
       }
   }, "Please use a personal email account");
   $.validator.addClassRules("emailrequired", {cRequired: true, email: true, domain: true});
 });
</script>

0 个答案:

没有答案