Search code examples
regexformsvalidationemailemail-validation

How can I do both email control and custom domain control with regex?


I want to check text which entered form field. Text must be valid email and shouldn't contain specific domain between "@" and "." sign. How can I do this with using regex? For example I want an email that shouldn't contain "test" domain

mail@mail => Invalid 
[email protected] => Invalid (Because contain 'test' domain)
[email protected] => Valid

HTML

<form>
    <input type="text" id="email">
    <button type="submit" id="sendMail">Send</button>
</form>

I can handle valid email with following pattern:

JS

const btn = document.getElementById('sendMail');

btn.addEventListener('click', (e) => {
    e.preventDefault();

  const emailPtrn = /^(([^<>()\[\]\\.,;:\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,}))$/;
  const email = document.getElementById('email');

  alert(emailPtrn.test(email.value));

});

JSfiddle Link

How can I check this with single pattern?


Solution

  • Just add (?!test\.) negative look ahead after @ in your current regex,

    ^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@(?!test\.)((\[[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,}))$
                                                                  ^^^^^^^^^^ This will reject any email if what follows immediately after @ is test.
    

    Regex Demo