gpt4 book ai didi

asp.net-mvc - 在 FluentValidation 中覆盖默认的 ASP.NET MVC 消息

转载 作者:行者123 更新时间:2023-12-04 14:50:25 30 4
gpt4 key购买 nike

我收到验证消息“值 xxx 对 yyy 无效”。当我为 double 类型发布不正确的值时会发生这种情况。我不知道如何改变它。

最佳答案

不幸的是,这不是 FluentValidation 能够覆盖的东西——MVC 验证的可扩展性模型在很多地方都有些限制,而且我还没有找到一种方法来覆盖这个特定的消息。

您可以使用的另一种方法是在 View 模型上定义两个属性 - 一个作为字符串,一个作为可为空的 double 。您可以将 string 属性用于 MVC 绑定(bind),而 double 属性将执行转换(如果可以的话)。然后,您可以使用它进行验证:

public class FooModel {
public string Foo { get; set; }

public double? ConvertedFoo {
get {
double d;
if(double.TryParse(Foo, out d)) {
return d;
}
return null;
}
}
}


public class FooValidator : AbstractValidator<FooModel> {
public FooValidator() {
RuleFor(x => x.ConvertedFoo).NotNull();
RuleFor(x => x.ConvertedFoo).GreaterThan(0).When(x => x.ConvertedFoo != null);
}
}

关于asp.net-mvc - 在 FluentValidation 中覆盖默认的 ASP.NET MVC 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7412101/

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