Combine two regular expression into one while validating Attribute

一曲冷凌霜 提交于 2019-12-02 07:31:52

问题


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.


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



来源:https://stackoverflow.com/questions/54780873/combine-two-regular-expression-into-one-while-validating-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!