简体   繁体   中英

Validate corporate emails in validate.js script

How is it possible to validate corporate emails in Validate.js plugin? To prevent users from entering a non-corporate emails. Of emails like @gmail.com, @yahoo.com, @hotmail.com.

That's the part of email validation in Validate.js main script:

email: function( value, element ) {
            return this.optional( element ) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test( value );
        }

A clean way to solve this is to extract the domain name into a variable (by taking a substring after the @) and then to check the value against an array of domains.

Doing this in a regex is creating a nightmare for whoever is going to read this code in the future!

Example:

var email = "name@example.com";
var domainName = email.slice((email.indexOf("@") + 1), email.length);

and then check if domainName is in the list of domains.

Add the exceptions and validate against them..

In your case, you can use multile regex and validate against them like this..

  var regex1 =   what-ever-regex-is-@yahoo.com
  var regex2 =   what-ever-regex-is-@hotmail.com
  var regex3 =   what-ever-regex-is-@gmail.com
  var regex4 =   what-ever-regex-is-@live.com

and use ! in-front of return..that means if one of them would be existing, your check would return true but ! will change the sign so that will be false and use it in your code accordingly.

 email: function( value, element ) {
        return (this.optional( element ) || 
 /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@yahoo.com$/.test( value ) 
    || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@hotmail.com$/.test( value )  );
    }

Another way could be to merge all of these knows domains in one regex and check against it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM