我想在我的班级中进行范围验证,即在我的课程中定义的范围值
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; }
}
如何获取要传递给我的类的MinRange和MaxRange的值 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) ))
}
答案 0 :(得分:0)
请参阅此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";);
}
}
答案 1 :(得分:0)
我找到了解决问题的方法。
实际上我需要当前对象的其他属性。
我们可以在Must
方法的一个重载中使用它:
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;
}
}