-1

I have a mailchimp subscription form, I am trying to validate the input value so it only accepts a specific type of email, @gmail.com for example.

[name]@gmail.com, if the user insert other than @gmail.com form should not be submitted, I tried to achieve this using regex but did not work, so how can I achieve such a function in JS.

Ahmad Tahhan
  • 125
  • 14

3 Answers3

2

This is doing what you want: /@gmail\.com$/

var test = [
    'abc@gmail.com',
    'abc@not_gmail.com',
];
console.log(test.map(function (a) {
  return a+' :'+/@gmail\.com$/.test(a);
}));
Toto
  • 89,455
  • 62
  • 89
  • 125
1

You can split and check part after @

var test = [
    'abc@gmail.com',
    'abc@not_gmail.com',
]

test.forEach(i => {
  console.log(i.split('@')[1] === 'gmail.com')
})
0

Agree with Toto's answer, but I would also like to check that the email prefix is correct using the regex from How to validate an email address using a regular expression?

var test = [
    'abc@gmail.com',
    'abc@not_gmail.com',
];
console.log(test.map(function (a) {
  return a + ': ' + /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@gmail\.com$/.test(a);
}));
Tianjiao Huang
  • 144
  • 3
  • 14