user1250264
user1250264

Reputation: 905

asp.net mvc validation annotation for int either must be 0 or greater than 100000

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

Answers (4)

Sudipto Sarkar
Sudipto Sarkar

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

Ric
Ric

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");
    }    
}

IValidatableObject.Validate

Upvotes: 0

user1075940
user1075940

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

Mike Ramsey
Mike Ramsey

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

Related Questions