Reputation: 111030
With JavaScript I want to take a input 1st validate that the email is valid (I solved for this) 2nd, validate that the email address came from yahoo.com
Anyone know of a Regex that will deliver the domain?
thxs
Upvotes: 11
Views: 41627
Reputation: 433
After reading previous answers and checking https://caniuse.com/mdn-javascript_builtins_string_endswith, the simplest way to check domain of an email is String.prototype.endsWith()
method.
A simple program to check different inputs can be like below:
function validateEmail(email: string): boolean {
return email.endsWith("example.com");
}
const emailCheckResults = new Map<string, boolean>();
const emailsToCheck = ["[email protected]", "[email protected]", "[email protected]"];
emailsToCheck.map((email) => {
emailCheckResults.set(email, validateEmail(email));
});
Array.from(emailCheckResults.keys()).map((key) => {
console.log(`Checked: ${key}, Result: ${emailCheckResults.get(key)}`);
});
This will result following:
Checked: [email protected], Result: true
Checked: [email protected], Result: false
Checked: [email protected], Result: false
Approaches like using indexOf
or split
simply didn't seem to me clean.
I recommend using String.prototype.endsWith()
method to avoid simple mistakes in regex, to improve readability and testability of the code, to reduce attack surface if this is used in an authentication system etc.
Upvotes: 1
Reputation: 1313
Domain name is mandatory like .com , .in , .uk It'll check update 2 letter after '.' and '@' is also mandatory.
<!DOCTYPE html>
<html>
<body>
<script>
function validateEmail(email) {
debugger;
console.log(email);
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
//return ture for .com , .in , .co upto 2 letter after .
console.log(re.test(String(email).toLowerCase()));
return re.test(String(email).toLowerCase());
}
</script>
<h2>Text field</h2>
<p>The <strong>input type="text"</strong> defines a one-line text input field:</p>
<form action="#" onSubmit="validateEmail(firstname.value)">
First name:<br>
<input type="email" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname">
<br><br>
<input type="submit">
</form>
<p>Note that the form itself is not visible.</p>
<p>Also note that the default width of a text field is 20 characters.</p>
</body>
</html>
Upvotes: 1
Reputation: 336378
var myemail = '[email protected]'
if (/@yahoo.com\s*$/.test(myemail)) {
console.log("it ends in @yahoo");
}
is true if the string ends in @yahoo.com
(plus optional whitespace).
Upvotes: 25
Reputation: 359
Try this:
/^\w+([\.-]?\w+)*@\yahoo.com/.test("[email protected]"); //Returns True
/^\w+([\.-]?\w+)*@\yahoo.com/.test("you@[email protected]"); //Returns false
/^\w+([\.-]?\w+)*@\yahoo.com/.test("you#[email protected]"); //Returns false
/^\w+([\.-]?\w+)*@\yahoo.com/.test("you/[email protected]"); //Returns false
Above are some test cases.
Upvotes: 1
Reputation: 24670
You do not need to use regex for this.
You can see if a string contains another string using the indexOf
method.
var idx = emailAddress.indexOf('@yahoo.com');
if (idx > -1) {
// true if the address contains yahoo.com
}
We can take advantage of slice()
to implement "ends with" like so:
var idx = emailAddress.lastIndexOf('@');
if (idx > -1 && emailAddress.slice(idx + 1) === 'yahoo.com') {
// true if the address ends with yahoo.com
}
In evergreen browsers, you can use the built in String.prototype.endsWith() like so:
if (emailAddress.endsWith('@yahoo.com')) {
// true if the address ends with yahoo.com
}
See the MDN docs for browser support.
Upvotes: 10
Reputation: 3381
For Yahoo domains (without username)
@(((qc|ca)?\.yahoo\.com)|yahoo\.(com(\.(ar|au|br|co|hr|hk|my|mx|ph|sg|tw|tr|vn))?|ae|at|ch|es|fr|be|co\.(in|id|il|jp|nz|za|th|uk)|cz|dk|fi|de|gr|hu|in|ie|it|nl|no|pl|pt|ro|ru|se))
Upvotes: 0
Reputation: 512
function emailDomainCheck(email, domain)
{
var parts = email.split('@');
if (parts.length === 2) {
if (parts[1] === domain) {
return true;
}
}
return false;
}
:)
Upvotes: 3
Reputation: 70721
To check for a particular domain (yahoo.com):
/^[^@\s][email protected]$/i.test(email)
// returns true if it matches
To extract the domain part and check it later:
x = email.match(/^[^@\s]+@([^@\s])+$/)
// x[0] contains the domain name
Upvotes: 2
Reputation: 19999
>>> String('[email protected]').replace(/^[^@]*@/, '')
'yahoo.com'
Upvotes: 0
Reputation: 102428
What about this?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<script type="text/javascript">
var okd = ['yahoo.com'] // Valid domains...
var emailRE = /^[a-zA-Z0-9._+-]+@([a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})$/
function ckEmail(tst)
{
var aLst = emailRE.exec(tst)
if (!aLst) return 'A valid e-mail address is requred';
var sLst = aLst[1].toLowerCase()
for (var i = 0; i < okd.length; i++) {
if (sLst == okd[i]) {
return true
}
}
return aLst[1];
}
var ckValid = ckEmail(prompt('Enter your email address:'))
if (ckValid === true) {
alert(ckValid) // placeholder for process validated
} else {
alert(ckValid) // placeholder for show error message
}
</script>
<title></title>
</head>
<body>
</body>
</html>
Upvotes: 0
Reputation: 1633
var rx = /^([\w\.]+)@([\w\.]+)$/;
var match = rx.exec("[email protected]");
if(match[1] == "yahoo.com"){
do something
}
second capturing group will contain the domain.
Upvotes: 1