ryan miller
ryan miller

Reputation: 105

Two Range Data annotations MVC

I'm trying use data annotations to validate a DropDown list in MVC. The values for the dropdown list range from 10-23 and then it can also be 99. Is there a way to use two range data annotations to only allow those possible values through?

something like

[Range(10-23)]
[Range(99-99)]
public int DropDownListValue { get; set; }

or is there a regular expression or something that can do this for me? Or would I just be better off making a custom validator?

Upvotes: 2

Views: 912

Answers (1)

adricadar
adricadar

Reputation: 10209

You can use a regular expression attribute to achieve this

[RegularExpression("^(1[0-9]|2[0-3]|99)$")]
public int DropDownListValue { get; set; }

Notes:

  1. 1[0-9] validates between 10 and 19
  2. 2[0-3] validates between 20 and 23
  3. 99 validates to be 99 :)
  4. You can add more validation with a | between them
  5. ^ and $ make sure that the entire string is validated (incorrect: a11a, a11, 11a) (correct: 11).

Upvotes: 2

Related Questions