Reputation: 27723
I need to validate email addresses, in addition to the basic structure, I need also
email address can not start or end with special character
email address can not have double special character edited special characters are
! # $ % & ' * + - / = ? ^ _ ` { | } ~
Character . ( period, dot or fullstop) provided that it is not the first or last character and it will not come one after the other.
So that's what I have so far that's just validates the basic structure
function emailIsValid (email) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
}
How do I add the above 2 conditions to it? Thank you
Edited valid addresses
[email protected]
[email protected]
[email protected]
[email protected]
invalid
@jen@gmail
jen@gmail
[email protected]
[email protected]
&[email protected]
[email protected].
Upvotes: 1
Views: 600
Reputation: 9137
You have three options.
This is probably the best choice. Ultimately, the only way to know if an email address is legit is to send a piece of unique data to that address and instruct the user to share that unique data with you, proving they have access to the mailbox (and thus that the mailbox exists, and thus that its address is legitimate).
I don't expect you to follow this advice.
You know, you don't have to do the entire job with a single regex. Doing so will actually be harder.
Since you've provided the list, here's an attempt at strategy 2:
const FORBIDDEN_TERMINAL_CHARACTERS = [
`!`,
`#`,
`$`,
`%`,
`&`,
`'`,
`*`,
`+`,
`-`,
`/`,
`=`,
`?`,
`^`,
`_`,
'`', // single quotes around tick
`{`,
`|`,
`}`,
`~`
]
function emailIsValid (email) {
let syntaxGood = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
if(!syntaxGood) return false // skip loop if we've already failed
for( let badChar of FORBIDDEN_TERMINAL_CHARACTERS ) {
if(email.startsWith(badChar) || email.endsWith(badChar)) {
return false // terminate early
}
}
return true
}
This is probably your second-best option.
This is a bad idea. Regular expressions are sometimes jokingly described as "write-only": the only person who can understand a regex is the person who wrote it, and even then only while they are actively creating it. Once it's in the rear-view mirror, they forget all the hairy contextual details, and it becomes opaque even to them. Good luck to future maintainers trying to modify this regex if, e.g. you want to add or remove one character to the list of forbidden ones. If you don't have a very robust set of automated test cases for this function, every future edit will probably break something.
The specifics of how to encode that regex will depend on the specific list of forbidden characters. So, if you want anyone on SO to attempt that code, you will have to provide the complete list.
Upvotes: 1