Skip to content

Instantly share code, notes, and snippets.

@portal7
Last active October 4, 2022 01:46
Show Gist options
  • Save portal7/4982b1140036db68c62d420f27e0e8b8 to your computer and use it in GitHub Desktop.
Save portal7/4982b1140036db68c62d420f27e0e8b8 to your computer and use it in GitHub Desktop.
jQuery Validator Email Domain
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>
<form id="myForm" name="myForm" action="#" method="POST"> <style>#email-error { display: block; color: red; }</style>
<label for="email">Email: </label>
<input id="email" name="email" type="email" minlength="6"/><br>
<input type="submit" value="Submit">
</form>
// Banning domains
var bannedDomains = ["spam.com", "junk.com"];
$.validator.addMethod('domainNotBanned', function(value, elem, param) {
var domain = value.split('@')[1];
return bannedDomains.indexOf(domain) < 0;
}, 'Emails from this domain are not allowed.');
// Banning specific addresses
var bannedEmails = ["mean@hacker.com", "kim.kardashian@gmail.com"];
$.validator.addMethod('emailNotBanned', function(value, elem, param) {
return bannedEmails.indexOf(value) < 0;
}, 'This email address is banned.');
// Applying these rules
$('#myForm').validate({
rules: {
email: {
required: true,
email: true,
domainNotBanned: true,
emailNotBanned: true
}
}
});
// Just for the demo
$('#myForm').on('submit', function(e) {
e.preventDefault();
alert("This email is valid.");
return false;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment