0

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 111@111.111
  2. The mail id should not be made up of special characters as ###@###.###
  3. It should validate something@something or some@some.com

Now I want a condition as

  1. There should only be two periods before and after @, which means some.some.some@heven.co.uk should be valid and some.some.some.some@heven.co.uk.gov should be invalid.

How to modify this regex for the above condition?

janw
  • 8,758
  • 11
  • 40
  • 62
  • [Don't use regex to validate email addresses](https://stackoverflow.com/questions/201323/how-to-validate-an-email-address-using-a-regular-expression) – vallentin Dec 26 '20 at 04:51
  • 1
    I concur that you should not try to validate email addresses except as an exercise. Validating email addresses is flawed and simply does not work because there are waaaay too many ways to make invalid ones that respect the rules and reject valid ones that don't. And the second issue is the deal breaker here: if you reject a valid one, your potential user will not change email address just to please you and you will lose him/her. – Andrea Raimondi Dec 26 '20 at 05:53

2 Answers2

1

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.

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

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,}))$/
janw
  • 8,758
  • 11
  • 40
  • 62
Vijay
  • 228
  • 3
  • 8