Nathan McKaskle
Nathan McKaskle

Reputation: 3083

Regular Expression Annotation Fails Despite Being Correct

In my model I have the following:

[Required(ErrorMessage = "First name is required.")]
[Display(Name = "First Name")]
[MaxLength(50)]
[RegularExpression(@"/^[A-z]+$/", ErrorMessage = "Only alphabet characters are allowed.")]
public string FirstName { get; set; }

In the form it's failing the check no matter what I put in there. I want it to just make sure there are only letters, no numbers or special characters.

This is not a duplicate because the referenced post has nothing to do with data annotations. They're two different contexts.

Upvotes: 1

Views: 448

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627537

You need to remove the regex delimiters (that are not used in .NET regex and are thus treated as literal slashes) and replace A-z with A-Za-z (see Why is this regex allowing a caret?).

Use

@"^[A-Za-z]+$"

Upvotes: 2

Related Questions