Search code examples
c#regexasp.net-mvcmodel-validation

Combine two regular expression into one while validating Attribute


I have two regular expression.

  1. [RegularExpression(@".*[^ ].*", ErrorMessage ="Something")] validate string that only contains spaces(Not any other characters Ex: " ".length = 7).
  2. [RegularExpression(@"^[^~!@#$%&*]+$", ErrorMessage = "something")] validate string that contains ~!@#$%&* special characters.

How can I combine both regex into one, because Duplicate Regular expression annotation is not allowed in asp.net mvc.


Solution

  • You may use

    ^[^~!@#$%&*]*[^~!@#$%&*\s][^~!@#$%&*]*$
    

    See the regex demo

    Details

    • ^ - start of string
    • [^~!@#$%&*]* - 0+ chars other than a char in the ~!@#$%&* list
    • [^~!@#$%&*\s] - a char other than a char in the ~!@#$%&* list and whitespace
    • [^~!@#$%&*]* - 0+ chars other than a char in the ~!@#$%&* list
    • $ - end of string.

    NOTE: To also allow an empty string you need to wrap the pattern between the anchors within an optional group: ^(?:[^~!@#$%&*]*[^~!@#$%&*\s][^~!@#$%&*]*)?$.