I am using MVC data annotations and my requirement is that the address field can contain any characters (i.e. other than English characters are also allowed) except < > . ! @ # % / ? *
.
I searched many sites but not getting how to write this regex.
So far I have tried:
[Required(ErrorMessage = "Address Required.")]
[RegularExpression(@"^[<>.!@#%/]+$", ErrorMessage = "Address invalid.")]
public string Address { get; set; }
$ means "Match the end of the string" (the position after the last character in the string).
Wildcard which matches any character, except newline (\n). Used to match 0 or more of the previous (e.g. xy*z could correspond to "xz", "xyz", "xyyz", etc.) ?!= or ?
A regular expression (shortened as regex or regexp; sometimes referred to as rational expression) is a sequence of characters that specifies a search pattern in text. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation.
Make your regex choose from any characters except the ones listed with the caret:
[^abc]
will match anything that's not an a, b, or c.
So putting it all together, your regex would be
^[^<>!@#%/?*]+$
Note here that the caret outside the square braces means 'match the start of the line', yet inside the square brackets means 'match anything that is not any of the following'
Try is regular expression:
[^<>.!@#%/?*]
Currently, you are only allowing string consisting ONLY of these letters.
Use
"^[^<>.!@#%/]+$"
This should do the work:
"[^<>.!@#%/]"
EDIT:
. (dot) is a reserved character in Regular Expressions, so you need to escape it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With