0

I have an HTML form that contains an input which requests a users email address. There are several email addresses that if entered should not allow the form to submit e.g. @donotsubmit.com, @donot.submit.com.

Using jQuery, is it possible to prevent the form from submitting if the input contains these strings? The code looks like this:

<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>

Edit:

Updated script using jQuery Array. The issue I am having is that the jQuery Validate is not using the inArray statement to mark the field as valid/invalid.

<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>
Tom Jones
  • 69
  • 1
  • 8
  • Yes, it's possible. However, I don't see where you've made any attempts. – Sparky May 09 '17 at 16:06
  • @Sparky, thank you for providing the feedback. I have amended the JS based on this but can't seem to get the array check to work, are you able to provide any help on this? – Tom Jones May 10 '17 at 14:52
  • 1
    The function within `.addMethod()` **must** always `return` a `true` or `false` indicating whether the input passed or failed validation. You have no such thing. See: https://jqueryvalidation.org/jQuery.validator.addMethod/ – Sparky May 10 '17 at 14:55
  • What on earth is the point of `.addMethod("cRequired")`? – Sparky May 10 '17 at 14:56
  • Thank you @Sparky, I was able to fix this using the link provided. – Tom Jones May 12 '17 at 12:20

0 Answers0