Reputation: 905
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
Upvotes: 0
Views: 772
Reputation: 356
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);
Upvotes: 0
Reputation: 13248
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");
}
}
Upvotes: 0
Reputation: 1125
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");
Upvotes: 0
Reputation: 843
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.
Upvotes: 1