1

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Sipun
  • 11
  • 5
  • @".*[^ ].*" : for space validation, I am using – Sipun Feb 20 '19 at 07:23
  • What's stopping you adding a space to the second expression? You want `~!@#$%& ` to all be invalid, right? – ProgrammingLlama Feb 20 '19 at 07:24
  • I did n't get you. second option? – Sipun Feb 20 '19 at 07:24
  • Then it will not allow space in my string. I need space but not string with only space. Like : " " : false " asdfa asdf " : true – Sipun Feb 20 '19 at 07:25
  • 1
    Something like `@"^(?=.*[^ ])[^~!@#$%&*]+$"` should work I guess. – Jerry Feb 20 '19 at 07:26
  • Can you add that to your question, because it's not clear that's what you want. – ProgrammingLlama Feb 20 '19 at 07:26
  • Ok. I will add it to question. https://stackoverflow.com/questions/54773228/c-sharp-string-should-not-contain-only-white-spaces-or-any-special-character-exc – Sipun Feb 20 '19 at 07:29
  • 1
    Possible duplicate of [C# string should not contain only white spaces or any special character except ,.';:"](https://stackoverflow.com/questions/54773228/c-sharp-string-should-not-contain-only-white-spaces-or-any-special-character-exc) – Sir Rufo Feb 20 '19 at 07:34
  • @Sipun Next time, please [**edit**](https://stackoverflow.com/posts/54780873/edit) your question if you want to add some details. – Sir Rufo Feb 20 '19 at 07:36
  • Ya, Its working. Thank you so much Jerry. – Sipun Feb 20 '19 at 08:33

1 Answers1

1

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][^~!@#$%&*]*)?$.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563