views:

24

answers:

2

I have 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: 

Have you tried changing your regex to:

"[A-Za-z]"
Ian Oxley
+1  A: 

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]$.

Ryan Brunner
I have edited my question to make clear I am only checking a single character that must be a capital letter.
arame3333
OK I found the problem. I was using CSS to enforce uppercase letters, see <%: Html.TextBoxFor(model => model.contract.ContractNo_Letter, new { maxlength = "1", style = "width:15px;text-transform: uppercase;" })%>However although visually this converts the letter on the screen, it doesn't do so in the underlying model. So [A-Za-z] is the correct answer. I will just have to make sure I have a setter on my field that converts the character to upper case when I save it.
arame3333
Personally, I'd still check the start and end on the regex. Your client currently prevents you from entering more than one character, but you shouldn't be relying solely on client-side validation.
Ryan Brunner
I think you are right about that. Best to be safe.
arame3333