0

I'm making an html5 form and only want users to sign up with .edu or .gov email addresses. What would the regex look like for that? I know it must be checked serverside as well, but one step at a time.

Example:

<input type="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" />
VLAZ
  • 26,331
  • 9
  • 49
  • 67

2 Answers2

0

Building on How to validate an email address in JavaScript? I came up with this using a simplified RFC 2822 compatible pattern:

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@((?!-)[A-Za-z0-9-]{0,62}[A-Za-z0-9]\.)+(edu|gov)

Regex Demo

The major difference is how the domain part is evaluated. I took this from my previous answer.

<form action="javascript:console.log('ok')">
<input type="text" name="domain" 
pattern="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@((?!-)[A-Za-z0-9-]{0,62}[A-Za-z0-9]\.)+(edu|gov)" title="Sorry, only email addresses from .edu and .org domains are allowed.">
<input type="submit">
</form> 
wp78de
  • 18,207
  • 7
  • 43
  • 71
0

Add this:

^[a-zA-Z0-9_.+-]+@(?:(?:[a-zA-Z0-9-]+\.)?[a-zA-Z]+\.)?(domain|domain2)\.(edu|gov)$

Demo

Nisarg
  • 1,631
  • 6
  • 19
  • 31