Search code examples
jqueryasp.net-mvc-3email-validation

Most efficient way to validate domain name in an email field in jquery?


I need to have just one validation in the email field, i.e domain name say 'something'.

Example:

[email protected] -valid
[email protected] - invalid

I have the emailid entered in the textbox stored as given below, Can you let me know the regular expression to have this basic above validation?

 var emailId = $('#txtRcpntAdress').val();

I am trying to use a reqular expression given below for the pattern.

var validDomain = "something";
var pattern = new RegExp("([A-Za-z0-9_\-\.])"+"@" + validDomain + "(.[a-zA-Z]{2,4})$");

It throws an error

Microsoft JScript runtime error: Invalid range in character set

Can you please help?

Thanks, Adarsh


Solution

  • This should do the trick:

       var validDomain = "something";
       var pattern = new RegExp("^[A-Za-z0-9_\\-\\.]+@" + validDomain + "(.[a-zA-Z\\.]{2,5})$");
       var emailId = "[email protected]";
    
       if( emailId.match(pattern) )
       {
         // ... email is valid
       }
    

    If you want to match the complete domain just change the first two lines:

       var validDomain = "something.com";
       var pattern = new RegExp("^[A-Za-z0-9_\\-\\.]+@" + validDomain + "$");