Balaji Telugunti
Balaji Telugunti

Reputation: 63

Dataannotations to restrict numbers only using mvc 4

Can I restrict user to enter only numbers using DataAnnotations?

Below is the property which I have in my Model

[Display(Name = "Fiscal Year")]
[Required(ErrorMessage = "Fiscal Year is required")]
public int FiscalYear { get; set; }

Below is the definition which I am using in .chtml (razor view):

@Html.TextBoxFor(model => model.project.FiscalYear)

I want to allow users only to enter numbers. Any suggestions?

Thanks, Balaji

Upvotes: 0

Views: 6800

Answers (2)

Yogiraj
Yogiraj

Reputation: 1982

Get the Nuget package called DataAnnotationsExtensions.. then use it like below:

    [Integer(ErrorMessage="This is needs to be integer")]
    public int CustomerId { get; set; }

It will put the proper the validation in place assuming that you have jQuery validation plugin and unobtrusive validation enabled.

Upvotes: 3

Ion Sapoval
Ion Sapoval

Reputation: 635

You can use RegularExpression attribute

Upvotes: 0

Related Questions