Question

I want to have range validation in my class that value of my range defined in my class

public class FieldViewModel
    {
        public string FieldName { get; set; }
        public string FieldValue { get; set; }
        public string MinRange { get; set; }
        public string MaxRange { get; set; }
        public List<int> Validations { get; set; } 

    }

how to get value of MinRange and MaxRange of my class to pass to InclusiveBetween(MinRange ,MaxRange )

public class FieldModelValidator : AbstractValidator<FieldViewModel> {

//!!!--MinRange and MaxRange  not recognized in InclusiveBetween
 RuleFor(x => x.FieldValue ) .InclusiveBetween(MinRange ,MaxRange ) .When(w => w.Validations.Any(x => x.Validations.Contain(2) ))

}
Was it helpful?

Solution 2

I found a way for my issue.

In fact i need other property of current object.

We can have it in one of the overloads of Must method:

public class FieldModelValidator : AbstractValidator<FieldViewModel> {
{ 
    public FieldModelValidator()
    {
        RuleFor(x => x.FieldValue).Must(RangeValidation).When(w => w.Validations.Any(x => x.Validations.Contain(2)))
    }

    private bool RangeValidation(FieldViewModel field, String value)
    {
        int val = int.Parse(value);

        if (val >= field.MinRange && val <= field.MaxRange)
        {
            return true;
        }

        return false;      
    }    
}

More Info

OTHER TIPS

See this article:

public class Validator
   {
       public AndClass IsNumber(int val)
       {
           int n;
           bool isNumeric = int.TryParse(val.ToString(), out n);
           if (isNumeric)
               return new AndClass( Convert.ToInt32(val));
           throw new Exception(";The value should be number";);
       }
   }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top