1

I need two ranges on an int in an MVC app

[Range(100, 200, ErrorMessage = "{0} must be between {1} and {2}")]
[Range(500, 600, ErrorMessage = "{0} must be between {1} and {2}")]
[Required(ErrorMessage = "Num Required")]
public int? Num { get; set; }

But only one Range DataAnnotation is allowed. How can I do this (ideally by using Data Annotations).

Can't find anything on Google.

thx.

niico
  • 11,206
  • 23
  • 78
  • 161
  • 1
    You would need to create you own validation attribute - refer [The Complete Guide To Validation In ASP.NET MVC 3 - Part 2](http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2) –  May 17 '17 at 09:43
  • http://stackoverflow.com/questions/16100300/asp-net-mvc-custom-validation-by-dataannotation – Ankush Jain May 17 '17 at 09:49

2 Answers2

1

You can use a regular expression to achieve this

for example for range
[Range(10-23)] [Range(99-99)]

you can use regular expression: [RegularExpression("^(1[0-9]|2[0-3]|99)$")]

Use following regular expression for your case:[RegularExpression("^(10[0-9]|1[1-9]\d|[5-6]\d\d)$")]

1

Beside custom annotations you can use IValidatableObject:

public class YourViewModel : IValidatableObject
{
   public int? Num { get; set; }
   .
   .
   .
   public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
   {
      if (Num == null)
          return true;

      if((Num.Value >= 100 && Num.Value <= 200) || (Num.Value >= 500 && Num.Value <= 600))
              return true;

      return false
   }
}
Mohsen Esmailpour
  • 11,224
  • 3
  • 45
  • 66