Reputation: 633
How can I annotate my model so I can allow only alphabets like A-Z in my text-box?
I know that I can use regex but can anyone show how to do that on text-box property itself using data annotation.
Upvotes: 17
Views: 72978
Reputation: 11614
You could write like this
It matches First character must be an alpha word
and following that matches any number of characters/hyphen/underscore/space
[RegularExpression(@"^[a-zA-Z]+[ a-zA-Z-_]*$", ErrorMessage = "Use Characters only")]
Upvotes: 1
Reputation: 256
You can use annotations for regular expression validation (if i understood your questions), something like that
[RegularExpression("[a-zA-Z]",ErrorMessage="only alphabet")]
Upvotes: 2
Reputation: 82287
You could annotate your model like this:
[RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
string TextBoxData {get; set;}
Then in your view you would use the helper
@Html.EditorFor(model => model.TextBoxData)
@Html.ValidationMessageFor(model => model.TextBoxData )
Upvotes: 52