learning...
learning...

Reputation: 3184

MVC5 StringLength validation failing on int

i have the following validations specified for an int field.

[Required(ErrorMessage = ValidationMessages.ResponseRequired)]
        [Digits(ErrorMessage = ValidationMessages.DigitsOnly)]
        [StringLength(6, MinimumLength = 6, ErrorMessage = ValidationMessages.InvalidLength)]
        public int? Code { get; set; }

When i take out the StringLength then the post is successful. With it, i get 500 exception:

Unable to cast object of type 'System.Int32' to type 'System.String'

What is going on here? Do i need to write a custom one for int? In this case, i just want to make sure that the user is entering 6 digits.

Upvotes: 0

Views: 1844

Answers (2)

AmirAkh
AmirAkh

Reputation: 11

You can use Range or RegularExpression for control your digits length.

Range[0,999999]  
Range[100000,999999]
[RegularExpression(@"\d{6}")]

Upvotes: 0

Stewart_R
Stewart_R

Reputation: 14515

String length isnt really valid for an int, though?

What is it that you are trying to achieve? That the input is greater than 99,999?

Then you can use:

[Range(100000,int.MaxValue)]

Upvotes: 1

Related Questions