Tushar Maheshwari
Tushar Maheshwari

Reputation: 80

Regular Expression for Email with Customized Conditions

Till now I have created a regular expression as

Pattern="^(?=.*[a-zA-Z].*)([a-zA-Z0-9._%+-]+@([a-zA-Z0-9-]+[a-zA-Z0-9-]+(\.([a-zA-Z0-9-]+[a-zA-Z0-9-])+)?){1,4})$"

which satisfies conditions as

  1. All should not be numbers as [email protected]
  2. The mail id should not be made up of special characters as ###@###.###
  3. It should validate something@something or [email protected]

Now I want a condition as

  1. There should only be two periods before and after @, which means [email protected] should be valid and [email protected] should be invalid.

How to modify this regex for the above condition?

Upvotes: 0

Views: 133

Answers (2)

The fourth bird
The fourth bird

Reputation: 163632

If the string should not consist of only digits, you can use a negative lookahead (?![\d@.]*$) to assert that there are not only digits, dots and @ signs until the the end of the string.

To match 0, 1 or 2 dots you can use a quantifier {0,2}.

The pattern uses \w to match word characters, but you can change it using a character class like [\w-%] to specify the allowed characters.

^(?![\d@.]*$)\w+(?:\.\w+){0,2}@\w+(?:\.\w+){0,2}$

Regex demo

Note that the pattern is very limited in accepting valid emails addresses. You could also make the pattern very broad and send a confirmation link to the user to verify it.

Upvotes: 1

Vijay Gangatharan
Vijay Gangatharan

Reputation: 298

This is the regex used to validate email with maximum constraints.

/^(([^<>()\[\]\\.,;:\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,}))$/

Upvotes: 0

Related Questions