0

I have an int that I want to validate with annotation in my model. It can be either 0 or greater than or equal to 100000. How can I do that?

Thanks

Bob Kaufman
  • 12,864
  • 16
  • 78
  • 107
user1250264
  • 897
  • 1
  • 21
  • 54
  • Share any code you may have so far and we can help attune the code to what works for your project. – Chad Feb 05 '16 at 14:33
  • There is no built-in annotation to do this. However should be easy to write a custom one – Andrei Feb 05 '16 at 14:35
  • 1
    Good question. Humble suggestion: ["zero is not null"](http://programmers.stackexchange.com/questions/134861/how-can-i-explain-the-difference-between-null-and-zero) Don't store zero when you mean nothing. – Bob Kaufman Feb 05 '16 at 14:35
  • Possible duplicate of [ASP MVC: Custom Validation Attribute](http://stackoverflow.com/questions/2720735/asp-mvc-custom-validation-attribute) – Dbl Feb 08 '16 at 08:38

4 Answers4

1

As others stated, there isn't one out of the box that does this that I am aware of, but there are several people that have written custom validation attributes that you can use. A good example that I have used in the past is from Lessthan Greaterthan Validation.

Mike Ramsey
  • 843
  • 8
  • 23
0

You have to write custom annotation but why to bother :) I highly recommend using Fluent Validation

Then solution for you problem would look like this:

RuleFor(x => x.Property)
                .GreaterThanOrEqualTo(0)
                .LessThanOrEqualTo(100000)
                .WithMessage("must be in range of 0-100000");
user1075940
  • 1,086
  • 2
  • 22
  • 46
0

You can implement IValidatableObject and provide your own customized validation:

Something like:

public class MyModel : IValidatableObject
{
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        //todo implement your logic here
             yield return new ValidationResult("Must be 0 or >= 1000");
    }    
}

IValidatableObject.Validate

Ric
  • 12,855
  • 3
  • 30
  • 36
0

I would recommend using Fluent Validation

using FluentValidation;
...

public class IntValidator : AbstractValidator<int>
{
    public IntValidator()
    {
        RuleFor(x => x.Property)
                        .Equal(0).GreaterThanOrEqualTo(100000)
                        .WithMessage("must be  0 or greater than 100000");
    }
}

Then

int intvariable;
IntValidator validator=new IntValidator();
ValidationResult result= validator.Validate(intvariable);
Tunaki
  • 132,869
  • 46
  • 340
  • 423
Sudipto Sarkar
  • 346
  • 2
  • 11