0

I made .edu email validation using this method - jQuery Form Validation, Only Allow .EDU Email Addresses

But instead of just .edu or just .edu.nn (where nn is a 2-digit country code), I would like to include both in one. Can't figure out how to achieve that. Below is the code that accepts both .edu and .edu.fr - I need to accept all other 2-digit country codes in addition to .edu

Thank you for your help!

$.validator.addMethod("edu", function (value, element, param) {
// Make it work optionally OR
//  Check the last 4 and 7 characters and ensure they match .edu and .edu.2-digit-country-code
return (this.optional(element) || value.slice(-4) == ".edu" || value.slice(-7) ==  ".edu.fr");
}, "Please enter valid .edu email address");

$("#requestform").validate({
    rules: {
        email: {
            required: true,
            email: true,
            edu: true
        },
    }
});    
Community
  • 1
  • 1
  • Are you planning on having an array of valid country codes? If not just remove the last condition, or change it to check that the last 2 characters are letters only – charlietfl Jan 06 '15 at 21:31

2 Answers2

1

Since .slice() will not be as performant as checking for both possibilities at once, using a RegExp with optional flags will be faster:

This regexp will match both conditions:

var regex = /\.edu(\.[a-z]{2})?$/

see here it working in the REPL:

> regex.test('somename.edu')
true
> regex.test('emai.com')
false
> regex.test('email.edu.cz')
true

Then your validator function will be small like this:

$.validator.addMethod("edu", function (value, element, param) {
    // Make it work optionally OR
    //  Check the last 4 and 7 characters and ensure they match .edu and .edu.2-digit-country-code
    return (value.match(/\.edu(\.[a-z]{2})?$/));
}, "Please enter valid .edu (or .edu.NN) email address");

And here is another site to test out your RegExp: http://regexpal.com/

Also, here are some explanation for the syntax of RegExp that I used:

x?: means match x 0 or more times (effectively x is optional)

x{N}: means match x exactly N times (used to match exactly 2 letters a-z)

$: means match 'end of input' (otherwise someacct.edu.fr@gmail.com would also match)

Hope it helped

aarosil
  • 4,848
  • 3
  • 27
  • 41
0

Use regular expression matching instead. Here is a great tool.

/.\edu.[a-z][a-z]/i

$.validator.addMethod("edu", function (value, element, param) {
// Make it work optionally OR
//  Check the last 4 and 7 characters and ensure they match .edu and .edu.2-digit-country-code
return (this.optional(element) || value.slice(-4).match(/\.edu/i) || value.slice(-7).match(/\.edu\.[a-z][a-z]/i);
}, "Please enter valid .edu email address");

$("#requestform").validate({
rules: {
    email: {
required: true,
email: true,
edu: true
},

    }
}); 
ZacWolf
  • 752
  • 5
  • 18