I’m looking to write a regular expression and my research online is taking me all over the place. Here’s what I’m looking to do:
[Required]
[RegularExpression("MyRegExString", ErrorMessage = "Use only valid characters.")]
public string Name { get; set; }
I want to allow my users to enter any alpha character (capital or lower case), and number, have spaces, and only _ (underscore), $, #, *, (, ), +, @, , (comma), and ‘ (apostrophe).
Can anyone help me generate this string?
Just enter them all into a character class and require that they the whole string consists of characters from this class (by putting
^and$anchors at the beginning and end, respectively):Regular expressions also have a built-in character class
\wthat matches letter (lower and upper case), digit or underscore, allowing for this slightly shorter version:Use
+instead of*at the end if you want to disallow empty strings.