Saturday 22 March 2014

jQuery Validate email is from a specific domain

I needed to validate that an email address provided via a form was from a user associated with a specific domain, I'll not repeat the domain and the example code I've included uses gmail.com but I'm pretty sure you'll be able to adapt it for your own purposes... and hopefully improve it. I found a number of possible solutions and enjoyed this idea from sectrean over on stackoverflow using Regular Expressions.

This was brilliant in terms of validation that the email address is/was an email address but didn't fulfil my requirement to check the domain of the the email address and didn't offer any more than the built in email method in the jQuery validation plugin. Then I clocked that Jacob Lauritzen had had a crack and that his work had been continued by Erik Woods with a nice little Fiddle.

Thus, on the backs of these giants I wrote this additional method for the Validation plugin, it needs some work and I'm thinking it may well have to accept and array of domains some time soon so I'm gonna have to have to do a wee bit more work on it, perhaps using the parems optional variable to addMethod. If you can think of improvements please don't hesitate to let me know.

jQuery.validator.addMethod("requireGmailEmail", function(value, element) {
    var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
    if (re.test(value)) {
        if (value.indexOf("@gmail.com", value.length - "@gmail.com".length) !== -1) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}, "Your email address is not valid.");

1 comment: