I’m trying to use a regular expression to validate a name entry field. The regular expression is very simple as I only want to allow letters and spaces (for now). Here’s the code that I’m using:
[RegularExpression("[A-Za-z\s]+",ErrorMessage="UserName can only consist of letters or spaces")]
[Required]
[DisplayName("User Name")]
public string UserName { get; set; }
When I try and build this, however, I get an error specifying an “Unrecognised escape sequence”. Playing around with the expression using different characters from this sheet I have noticed that some will build and some will not:
Will build: // /b /n
Will not build: /s /k /B /D /d /? /(escaped space)
Can anyone explain why some of these work and some do not and more to the point how can I get my desired expression to work (spaces and letters)
The compiler is treating the string exactly as it normally would for backslashes. Your backslash is an entry to an escape character. Try this:
The @ symbol tells the compiler that you’re handling any escape characters.
Another example is file paths.. backslashes must be escaped with a double backslash:
..otherwise, you can use the @ symbol: