fluentvalidation更改int/long的默认错误消息 [英] fluentvalidation change default error message for int/long

查看:76
本文介绍了fluentvalidation更改int/long的默认错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以更改FluentValidation中in的默认错误消息?

我们能够为更复杂的类型设置验证,但是我们似乎无法理解的简单的您输入的数据不是int"风格的东西.

这些的内置错误是:"x值对y无效"或类似的含义-是否有方法可以覆盖这些值?

解决方案

没有简单/干净的方法来实现.第一种可能性是在应用程序启动时覆盖 DefaultModelBinder.ResourceClassKey 属性,并将其指向自定义资源文件:

protected void Application_Start()
{
    RegisterRoutes(RouteTable.Routes);
    DefaultModelBinder.ResourceClassKey = "Messages";
}

,然后在App_GlobalResources/Messages.resx内定义键PropertyValueInvalid.

另一种可能性是按照杰里米·斯金纳(Jeremy Skinner)的建议,在视图模型上使用后备字段.

其原因是此错误消息是由默认模型绑定程序生成的,然后才能在该字段上进行任何验证.在验证字段之前,必须先为其分配一个值.而且,由于您试图在模型绑定期间将不代表有效整数的字符串转换为整数,因此默认模型绑定器会分配默认消息.

Is there a way to change the default error message for an in in FluentValidation?

We are able to set up validations for more complex types but the simple 'the data you entered isn't an int' style things we can't seem to get at.

The built in error for these is: 'the value x isn't valid for y' or something along those lines - is there a way to override these?

解决方案

There's no easy/clean way to achieve that. The first possibility is to override the DefaultModelBinder.ResourceClassKey property in your application start and point it to a custom resource file:

protected void Application_Start()
{
    RegisterRoutes(RouteTable.Routes);
    DefaultModelBinder.ResourceClassKey = "Messages";
}

and then define the key PropertyValueInvalid inside App_GlobalResources/Messages.resx.

Another possibility is to use a backing field on your view model as suggested by Jeremy Skinner.

The reason for this is that this error message is generated by the default model binder before any validation can occur on the field. Before you can validate the field it must first be assigned a value. And since you are attempting to convert a string which doesn't represent a valid integer into an integer during model binding, the default model binder assigns a default message.

这篇关于fluentvalidation更改int/long的默认错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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