16

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
updev
  • 623
  • 5
  • 14
  • 32

3 Answers3

51

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 )
Travis J
  • 81,153
  • 41
  • 202
  • 273
2

You can use annotations for regular expression validation (if i understood your questions), something like that

        [RegularExpression("[a-zA-Z]",ErrorMessage="only alphabet")]
diegoe
  • 256
  • 2
  • 8
1

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")]
Praveen M P
  • 11,314
  • 7
  • 34
  • 41