'Validating email that has @something.co.uk
I have the following regex options:
let emailValid = "/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/"
emailValid = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$"
emailValid = `/^(([^<>()[\]\\.,;:\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,}))$/`
emailValid = "/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/"
And none are able to consistently reject @somethingcouk
while accepting @something.co.uk
The advice given here is just plain wrong https://www.w3resource.com/javascript/form/email-validation.php
It suggests /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
which, according to them, should accept [email protected]
, but in my case it does not accept [email protected]
.
I'd like not to spend 3 days learning the regex to do this, when various tutorials and stack overflow answers are already given. What am I doing wrong here?
Does inputting these as a variable, without using match()
, as some places suggest, affect the functionality?
Solution 1:[1]
The options you list are all strings.
While there are cases where you can convert a string to a regular expression, your approach is breaking all the escape characters (because a \
starts an escape sequence in both strings and regular expressions.
Use a regular expression literal instead:
const emailValid = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
Possibly not that one though because top-level domain names are no longer restricted to 2 or 3 characters. There's a reason that the email address validation browsers apply to input type=email
generally isn't any more complex than "Contains an @
sign".
Solution 2:[2]
I have made this long time ago and this also accept email address for ip domain like [email protected]
function checkEmailPattern(str) {
const pattern = /^([^\.\_\-\@])+([^\.\@\_\-])*((([^\d\@]){0,1})[a-z0-9]{2,}){0,1}((@([a-zA-Z]{2,})+(\.([a-z]{2,})){1,2}|@(\d{3}.){1,3})|(@([0-9]{1,3})+(\.([0-9]{1,3})){3}))$/;
return pattern.test(str.toLowerCase());
}
let value1 = '[email protected]';
console.log(checkEmailPattern(value1)); // true
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Quentin |
Solution 2 | Jafar Pager Jaya |