Reputation: 442
I have a very simple contact from but for the business requirement we need to validate the company's url with the contacting user's email
If your email is [email protected] and your url is http://examplecompany.com, the form will go through.
I'm trying to do it using regex, but I can't for the life of me, figure out what I'm doing wrong.
Here's my code so far:
validateEmail = (email, url) => {
let rootUrl = url.match(/^(?:https?:\/\/)?(?:[^@\/\n]+@)?(?:www\.)?([^:\/?\n]+)/)[1];
let emailDomain = email.match(/@(.*)/)[1];
return rootUrl === emailDomain;
}
My emailDomain is returning undefined
.
Upvotes: 0
Views: 233
Reputation: 1807
I tried to implement it with regex as following.
const validateEmail = (email, url) => {
let regex = /(https?:\/\/)?(\w*\.)?(\w*\.\w*)/
let rootUrl = url.match(regex)[3];
let emailDomain = email.match(/@(.*)/)[1];
return rootUrl === emailDomain;
}
// Testing
let emails = ["[email protected]", "[email protected]"]
let urls = ["http://examplecompany.com", "https://examplecompany.com", "http://www.examplecompany.com", "https://www.examplecompany.com","examplecompany.com", "www.examplecompany.com"]
urls.forEach((url) => {
emails.forEach((email) => {
let valid = validateEmail(email, url)
console.log(`email = ${email}, url = ${url}, isValid: ${valid}`)
})
})
You could also try to use URL api (of course, it doesn't work on IE) to extract the hostname, and then extract domain name to compare with email address's domain name.
Upvotes: 3