To add email validation with JavaScript, we can check our strings against a simple regex with the test
method.
For instance, we can write:
const email = 'abc@abc.com'
if (/(.+)@(.+){2,}\.(.+){2,}/.test(email)) {
console.log('valid')
} else {
console.log('invalid')
}
to define the email regex with:
/(.+)@(.+){2,}\.(.+){2,}/
The regex just matches any string with characters before and after the @
sign.
After the @
sign, we also, check if there’re 2 or more characters after the dot for the domain extension.
Then we call test
on the regex with email
to check if email
is a valid email string.
Therefore, we should see 'valid'
logged since it’s a valid email.