Reputation: 14909
I have a form field that is optional, but if someone enters data, they have to enter 8 integers only.
What kind of model annotation should I use for this?
Upvotes: 0
Views: 266
Reputation: 23626
Try to use Range attribute, which work properly with nullable types. Specify upper and lower range for your number. Note that if Required is absent - this field is optional.
[Range(10000000, 99999999, ErrorMessage = "Number must be exactly 8 digit long")]
public int? Field {get; set;}
Upvotes: 1
Reputation: 9002
Try this regex expression: ^\d{8}?$
It allows input only 8 digits or nothing.
Upvotes: 0
Reputation: 819
You could try the regular expression attribute with the following regex:
[RegularExpression(@"\d{8}?")]
This means 8 digits, but it's optional
Upvotes: 0