MVC 2 RegularExpression for a single letter is not working
I h开发者_Python百科ave a Regular Expression Validation for a Single Capital Letter, but it does not work. When I put in a valid letter, I get the error message;
[DisplayName("Contract Letter")]
[RegularExpression("[A-Z]", ErrorMessage = "Must be a letter")]
[Required(ErrorMessage = "A Letter is required")]
public string ContractNo_Letter { get; set; }
I am only allowing the input of 1 letter.
A couple of things to consider here:
- The regular expression you have specified will evaluate to true provided that there is at least one letter from A-Z anywhere within the expression. For example:
8979*(&#$HJ
will evaluate to true. To match exactly one letter, you can wrap your regex with the special characters:^
(start of line), and$
(end of string). - Regular expressions in DataAnnotations are case-sensitive. To check both upper and lower-case letters, use
[A-Za-z]
.
So, to match a single letter without case sensitivity, use ^[A-Za-z]$
.
Have you tried changing your regex to:
"[A-Za-z]"
精彩评论