在FluentValidation覆盖默认ASP.NET MVC消息 [英] Override default ASP.NET MVC message in FluentValidation

查看:228
本文介绍了在FluentValidation覆盖默认ASP.NET MVC消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到验证消息的值xxx是无效YYY。当我张贴double类型不正确的值它发生。我不知道如何去改变它。

I get the validation message "The value xxx is not valid for yyy". It happens when I post incorrect value for double type. I have no idea how to change it.

推荐答案

可惜,这不是一件FluentValidation具有覆盖能力 - 对MVC的验证扩展性模型在很多地方有所限制,我也没有能够找到一种方法来覆盖这个特殊的消息。

Unfortunately this isn't something that FluentValidation has the ability to override - the extensibility model for MVC's validation is somewhat limited in many places, and I've not been able to find a way to override this particular message.

您可以使用另一种方法是在您的视图模型中定义两个属性 - 一个作为一个字符串,一个作为可空双。你会使用字符串属性MVC结合的目的,和双属性将执行转换(如果可以)。然后,您可以使用此进行验证:

An alternative approach you could use is to define two properties on your view model - one as a string, and one as a nullable double. You would use the string property for MVC binding purposes, and the double property would perform a conversion (if it can). You can then use this for validation:

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

这篇关于在FluentValidation覆盖默认ASP.NET MVC消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆