Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model Validation to allow only alphabet characters in textbox

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.

like image 422
updev Avatar asked Mar 22 '12 21:03

updev


People also ask

How do I make a textbox that only accepts alphabets?

Add a KeyPress event handler on the TextBox. Then put in this code into the textbox. This will allow only alphabets or /.


2 Answers

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 )
like image 118
Travis J Avatar answered Sep 20 '22 01:09

Travis J


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

        [RegularExpression("[a-zA-Z]",ErrorMessage="only alphabet")]
like image 40
diegoe Avatar answered Sep 21 '22 01:09

diegoe