Data Annotation MVC3

2019-07-20 06:08发布

问题:

Is it possible to use DataAnnotations to restrict user from enter special character?

I want the user to enter only A-Z, a-z and 0-9 into a textbox.

I need to do this on the client side.

回答1:

yes you can use Regular Expression for that...

[Required(ErrorMessage = "Enter Foo !")]
[RegularExpression(@"^[a-zA-Z0-9]+$", ErrorMessage = "Incorrect Entry dude !")]
public string Foo { get; set; }


回答2:

You could try using the [RegularExpression] attribute:

[RegularExpression(@"^[a-zA-Z0-9]+$")]
public string Foo { get; set; }

It supports unobtrusive client side validation as well, so this regex will be transposed on the client.



回答3:

I'm pretty sure there's a RegularExpression attribute for that, not sure how well it works with client-side tho.

[RegularExpression(@"your-reg-exp", ErrorMessage = "Your error message")]