1

I have a view model like this:

public class IndexVM
{
  [Required]
  // Must be either a 0, 5, 10, 25 or 50
  public int RadiusInMile { get; set; }
}

How can I tell MVC that the int must be either a 0, 5, 10, 25 or a 50? For anything other than those values ModelState.IsValid ought to return false.

I know about the Range[] validation attribute, but doesn't really work for me because I don't have a smooth range.

halfer
  • 19,471
  • 17
  • 87
  • 173
J86
  • 13,151
  • 40
  • 123
  • 206
  • I'm just curious, what would you want to happen if you try to set it to something else. Shall it crash, throw an exception or just round it? – D. Petrov Jun 28 '16 at 12:38
  • 4
    try [custom validation](http://stackoverflow.com/questions/16100300/asp-net-mvc-custom-validation-by-dataannotation) – Rafal Jun 28 '16 at 12:38
  • @D.Petrov I'd just return the user to the form like normally happens with an error message along the lines of `Your requested radius is not acceptable`. The user on the form select the radius from a pre-populated drop down of accepted values, but this is for validation purposes. – J86 Jun 28 '16 at 12:40
  • 2
    You could use a `[RegularExpression]` attribute. But a custom validation attribute would be more flexible –  Jun 28 '16 at 12:41
  • 1
    Thanks, I hadn't thought about Regular Expressions! Going to try this `[RegularExpression("^(0|5|10|25|50)$", ErrorMessage = "Please stick to values in the drop down for radius")]` – J86 Jun 28 '16 at 12:47

0 Answers0