I have this code to validate email input. My problem is, I want my form to accept only one specific domain. Such as, for example, [email protected]. I have no idea how to do this. Here's what I have so far:
function validateEmail(email)
{
var splitted = email.match("^(.+)@(.+)$");
if (splitted == null) return false;
if (splitted[1] != null)
{
var regexp_user = /^\"?[\w-_\.]*\"?$/;
if (splitted[1].match(regexp_user) == null) return false;
}
if (splitted[2] != null)
{
var regexp_domain = /^[\w-\.]*\.[A-Za-z]{2,4}$/;
if (splitted[2].match(regexp_domain) == null)
{
var regexp_ip = /^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
if (splitted[2].match(regexp_ip) == null) return false;
} // if
return true;
}
return false;
}
I have this code to validate email input. My problem is, I want my form to accept only one specific domain. Such as, for example, [email protected]. I have no idea how to do this. Here's what I have so far:
function validateEmail(email)
{
var splitted = email.match("^(.+)@(.+)$");
if (splitted == null) return false;
if (splitted[1] != null)
{
var regexp_user = /^\"?[\w-_\.]*\"?$/;
if (splitted[1].match(regexp_user) == null) return false;
}
if (splitted[2] != null)
{
var regexp_domain = /^[\w-\.]*\.[A-Za-z]{2,4}$/;
if (splitted[2].match(regexp_domain) == null)
{
var regexp_ip = /^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
if (splitted[2].match(regexp_ip) == null) return false;
} // if
return true;
}
return false;
}
Share
Improve this question
edited Dec 17, 2012 at 7:42
Jenna Pink
asked Dec 17, 2012 at 5:41
Jenna PinkJenna Pink
611 gold badge2 silver badges4 bronze badges
2
- 1 How about a simple, if( email.indexOf('@thisdomainonly') > 0) – Akhil Sekharan Commented Dec 17, 2012 at 5:50
- If this is about security this is dangerous, as one could easily create a subdomain with @thisdomainonly..myrealdomain. – Jeroen van Dijk Commented Dec 16, 2015 at 9:40
2 Answers
Reset to default 5Modifying your function, you'd use something like this:
function validateEmail(email)
{
var splitted = email.match("^(.+)@thisdomainonly\.$");
if (splitted == null) return false;
if (splitted[1] != null)
{
var regexp_user = /^\"?[\w-_\.]*\"?$/;
if (splitted[1].match(regexp_user) == null) return false;
return true;
}
return false;
}
But a more efficient version would be:
function validateEmail(email){
return /^\"?[\w-_\.]*\"?@thisdomainonly\.$/.test(email);
}
How about a simple indexOf checking:
function checkEmail(email, domainName){
if(email.indexOf(domainName) > 0)
if((email.indexOf(domainName) + domainName.length) == email.length){
//do regex checking if any
return true;
}
alert('Please enter a valid email for : '+ domainName)
return false;
}