Multiple Conditions in Validation Regex

46,787

Use this:

^(?=\S)(?=(?:[^+]*\+){0,2}[^+]*$)(?=(?:[^(]*\()?[^(]*$)(?=(?:[^)]*\))?[^)]*$)[- .()+0-9]*[-.+()0-9]$

In the regex demo you can play with the input to check what matches and doesn't.

Explanation

  • The ^ anchor asserts that we are at the beginning of the string
  • The lookahead (?=\S) asserts that what follows is a non-space character
  • Lookahead (?=(?:[^+]*\+){0,2}[^+]*$) : two + chars at the most
  • Lookahead (?=(?:[^(]*\()?[^(]*$) : One ( at the most
  • Lookahead (?=(?:[^)]*\))?[^)]*$) : One ) at the most
  • [- .()+0-9]* zero or more of the allowed chars
  • [-.+()0-9] end with one of the allowed chars that is not a space
  • The $ anchor asserts that we are at the end of the string

Reference

Share:
46,787
rkoller
Author by

rkoller

Updated on July 09, 2022

Comments

  • rkoller
    rkoller almost 2 years

    I am more or less a regex novice. I tried to get the following conditions into a regex:

    • No White Space at the beginning and at the end of a string
    • Allow all digits
    • Allow spaces, points, brackets, plus and minus

    Resulted in the following regex:

    ^\S[\d\/. ()\-+]*\S$
    

    But now i try to apply two more conditions:

    • Allow only one or two +
    • Allow only one ( and one )

    My problem is how to merge those two conditions into the existing regex string above cuz excluding + [+]{1,2} and () [(]{1} [)]{1} doesn't make much sense cuz i try to make general statements in no particular order so that i would be able to chain it. Thanks Ralf

  • zx81
    zx81 almost 10 years
    Thank you, glad it helped. :)
  • rkoller
    rkoller almost 10 years
    Thanks a lot! Works exactly as planned. But i think i have to work through your explanations to actually understand everything. A few new bits i haven't seen yet. ;)
  • zx81
    zx81 almost 10 years
    I recommend you start with the second article in the reference section as the explanation is at a much more comfortable pace. The technique is the same—this is similar to a password-validation regex.
  • rkoller
    rkoller almost 10 years
    Yep the first link i already knew, ran across it a few hours ago while researching. But it's a bit too high paced. The other link seems much more suitable for my current level. Perfect. Thanks a lot...