Maykel Esser
Maykel Esser

Reputation: 319

Email Validation with HTML5 Required Attribute plus Regular Expression Pattern

I'm using the native HTML5 validation for an "email" field and it works fine! However, I would like to increase it to a specific case, where I do not want to accept emails with "free" domains (gmail, hotmail, etc).

I did the regular expression and tested it and it worked correctly (Here you can do the test: https://regex101.com/r/wBt3YN/1). But when applying to the pattern of the email field, nothing happens.

How to proceed?

Some strings:

[email protected] -> Can't allow

[email protected] -> Can allow

[email protected] -> Can't allow

Regex Pattern

^([\w-.]+@(?!gmail\.com)(?!yahoo\.com)(?!hotmail\.com)(?!mail\.com)(?!live\.com)(?!aol\.com)(?!outlook\.com)(?!bol\.com)(?!msn\.com)(?!ymail\.com)([\w-]+.)+[\w-]{2,4})?$

My form

<form>
  <div class="field">
    <label for="email">Email Corporativo</label>
        <input 
          type="email" 
          name="email" 
          id="email" 
          value="" 
          pattern="^([\w-.]+@(?!gmail\.com)(?!yahoo\.com)(?!hotmail\.com)(?!mail\.com)(?!live\.com)(?!aol\.com)(?!outlook\.com)(?!bol\.com)(?!msn\.com)(?!ymail\.com)([\w-]+.)+[\w-]{2,4})?$" 
          title="Utilize seu email corporativo" 
          placeholder="" 
          required
        >
  </div>
  <input type="submit" value="ENVIAR">
</form>

Upvotes: 0

Views: 1268

Answers (1)

enxaneta
enxaneta

Reputation: 33054

Here is my code where I do not allow yahoo & hotmail. However, e-mail validation is a very delicate thing.

<form>
  <div class="field">
    <label for="email">Email Corporativo</label>
        <input 
          type="email" 
          name="email" 
          id="email" 
          value="" 
          pattern="^[^@]+@(?!(yahoo|hotmail))[^@]+\.[a-z]{2,}$" 
          title="Utilize seu email corporativo" 
          placeholder="" 
          required
        >
  </div>
  <input type="submit" value="ENVIAR">
</form>

Upvotes: 2

Related Questions