gpt4 book ai didi

asp.net-mvc - 使用 FluentValidation 根据类型更改验证

转载 作者:行者123 更新时间:2023-12-03 04:34:06 25 4
gpt4 key购买 nike

我有一个像这样的简单模型:

[Validator(typeof(EntryModelValidator))]
public class EntryModel : BaseNopEntityModel
{
public virtual string ProductActionValue { get; set; }
}

我正在使用 FluentValidation 来验证模型的保存。问题是,当用户在表单上保存值时,在某些情况下 ProductActionValue 需要保存为 int (当然它总是保存为字符串,但它需要可解析为 int)。

我有以下验证规则,可确保该值不为空:

 RuleFor(x => x.ProductCriteriaValue)
.NotEmpty()
.WithMessage(localizationService.GetResource("Common.FieldRequired"));

我尝试添加以下规则来验证 int:

 RuleFor(x => Int32.Parse(x.ProductCriteriaValue))
.GreaterThanOrEqualTo(1)
.When(x => (ProductCriteriaTypes)x.ProductCriteriaTypeId == ProductCriteriaTypes.ProductCreatedGreaterThanXDays || (ProductCriteriaTypes)x.ProductCriteriaTypeId == ProductCriteriaTypes.ProductCreatedLessThanXDays)
.WithMessage(localizationService.GetResource("Common.FieldRequired"));

但这只会引发 FluentValidation 运行时错误。有办法实现这个目标吗?

提前致谢铝

更新以反射(reflect)艾哈迈德的解决方案:

   {
RuleFor(x => x.ProductCriteriaValue)
.Must(BeANumber)
.WithMessage(localizationService.GetResource("Common.FieldRequired"));
}

private bool BeANumber(string value)
{
int result;
if (Int32.TryParse(value, out result))
{
return result >= 1;
}
return false;
}

最佳答案

您可以使用Predicate Validator (aka Must) :

RuleFor(x => x.ProductCriteriaValue)
.Must(x => Int32.Parse(x.ProductCriteriaValue) >= 1)
.When(x => (ProductCriteriaTypes)x.ProductCriteriaTypeId == ProductCriteriaTypes.ProductCreatedGreaterThanXDays || (ProductCriteriaTypes)x.ProductCriteriaTypeId == ProductCriteriaTypes.ProductCreatedLessThanXDays)
.WithMessage(localizationService.GetResource("Common.FieldRequired"));

当然,这是假设解析不会失败。 ProductCriteriaValue 总是一个数字并且可以正常解析吗?如果是这样,那就可以了。否则,您可能需要使用 Int32.TryParse 并按如下方式更改谓词来更好地检查这一点:

    .Must(x =>
{
int result;
if (Int32.TryParse(x.ProductCriteriaValue, out result))
{
return result >= 1;
}
return false;
})

关于asp.net-mvc - 使用 FluentValidation 根据类型更改验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13974843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com