如何更改“数据值编号” MVC 中的消息验证,由 @Html 帮助程序生成
假设这个模型:
Public Class Detail
...
<DisplayName("Custom DisplayName")>
<Required(ErrorMessage:="Custom ErrorMessage")>
Public Property PercentChange As Integer
...
end class
并且视图:
@Html.TextBoxFor(Function(m) m.PercentChange)
将继续这个html:
<input data-val="true"
data-val-number="The field 'Custom DisplayName' must be a number."
data-val-required="Custom ErrorMessage"
id="PercentChange"
name="PercentChange" type="text" value="0" />
我想自定义 data-val-number
错误消息,我猜它已经生成,因为 PercentChange
是一个 整数
。我一直在寻找这样的属性来更改它,range
或任何相关的内容都不起作用。
我知道有机会编辑 unobtrusive 的 js 文件本身或在客户端覆盖它。我想像服务器端的其他错误消息一样更改 data-val-number
的错误消息。
Assume this model:
Public Class Detail
...
<DisplayName("Custom DisplayName")>
<Required(ErrorMessage:="Custom ErrorMessage")>
Public Property PercentChange As Integer
...
end class
and the view:
@Html.TextBoxFor(Function(m) m.PercentChange)
will proceed this html:
<input data-val="true"
data-val-number="The field 'Custom DisplayName' must be a number."
data-val-required="Custom ErrorMessage"
id="PercentChange"
name="PercentChange" type="text" value="0" />
I want to customize the data-val-number
error message which I guess has generated because PercentChange
is an Integer
. I was looking for such an attribute to change it, range
or whatever related does not work.
I know there is a chance in editing unobtrusive's js file itself or override it in client side. I want to change data-val-number
's error message just like others in server side.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(14)
一个简单的方法是,在 ViewModel 上使用 dataannotation 更改消息:
a simple method is, use dataanotation change message on ViewModel:
我在 KendoGrid 中遇到这个问题,我在视图末尾使用脚本来覆盖 data-val-number:
至少,在视图末尾我放置:
I have this problem in KendoGrid, I use a script at the END of View to override data-val-number:
And at least, in the end of View I put:
我把这个放在我的观点上
I make this putting this on my view
或者你可以简单地这样做。
希望这有帮助。
Or you can simply do this.
Hope this helps.
我刚刚这样做了,然后使用了正则表达式:
I just did this and then used a regex expression:
也看看这个:
ASP.NET MVC 3 中的验证完整指南 - 第 2 部分
本文的主要部分如下(复制粘贴)。
创建可在客户端和服务器上运行的功能齐全的自定义验证器有四个不同的部分。首先,我们对 ValidationAttribute 进行子类化并添加服务器端验证逻辑。接下来,我们在属性上实现
IClientValidatable
,以允许将 HTML5data-*
属性传递给客户端。第三,我们编写一个自定义 JavaScript 函数来在客户端执行验证。最后,我们创建一个适配器来将 HTML5 属性转换为我们的自定义函数可以理解的格式。虽然这听起来工作量很大,但一旦开始,您就会发现它相对简单。子类化 ValidationAttribute
在此示例中,我们将编写一个 NotEqualTo 验证器,它仅检查一个属性的值是否不等于另一个属性的值。
将新属性添加到 RegisterModel 的密码属性并运行应用程序。
实现 IClientValidatable
ASP.NET MVC 2 有一个添加客户端验证的机制,但它不是很漂亮。值得庆幸的是,在 MVC 3 中,情况有所改善,该过程现在相当简单,而且幸运的是,不涉及到像以前版本中那样更改
Global.asax
。第一步是让您的自定义验证属性实现 IClientValidatable。这是一个简单的单一方法界面:
如果您现在运行应用程序并查看源代码,您将看到密码输入 html 现在包含您的
notequalto
数据属性:创建自定义 jQuery 验证函数
所有这些代码最好放置在单独的 JavaScript 文件中。
根据您的验证要求,您可能会发现 jquery.validate 库已经具有验证本身所需的代码。 jquery.validate 中有很多验证器尚未实现或映射到数据注释,因此如果这些验证器满足您的需求,那么您需要在 javascript 中编写的只是一个适配器,甚至是对内置适配器的调用,它可以只需一行即可。查看jquery.validate.js内部以了解可用的内容。
使用现有的 jquery.validate.unobtrusive 适配器
适配器的工作是读取表单元素上的 HTML5
data-*
属性,并将此数据转换为可以可以通过 jquery.validate 和您的自定义验证函数来理解。不过,您不需要自己完成所有工作,在许多情况下,您可以调用内置适配器。 jquery.validate.unobtrusive 声明了三个可在大多数情况下使用的内置适配器。它们是:如果您的验证器不属于这些类别之一,则需要使用 jQuery.validator.unobtrusive.adapters.add 方法编写自己的适配器。这并不像听起来那么困难,我们将在本文后面看到一个示例。
我们使用 addSingleVal 方法,传入适配器的名称和我们要传递的单个值的名称。如果验证函数的名称与适配器不同,您可以传入第三个参数 (
ruleName
):至此,我们的自定义验证器就完成了。
为了更好地理解,请参阅 文章本身提供了更多描述和更复杂的示例。
HTH。
Check this out too:
The Complete Guide To Validation In ASP.NET MVC 3 - Part 2
Main parts of the article follow (copy-pasted).
There are four distinct parts to creating a fully functional custom validator that works on both the client and the server. First we subclass
ValidationAttribute
and add our server side validation logic. Next we implementIClientValidatable
on our attribute to allow HTML5data-*
attributes to be passed to the client. Thirdly, we write a custom JavaScript function that performs validation on the client. Finally, we create an adapter to transform the HTML5 attributes into a format that our custom function can understand. Whilst this sounds like a lot of work, once you get started you will find it relatively straightforward.Subclassing ValidationAttribute
In this example, we are going to write a NotEqualTo validator that simply checks that the value of one property does not equal the value of another.
Add the new attribute to the password property of the RegisterModel and run the application.
Implementing IClientValidatable
ASP.NET MVC 2 had a mechanism for adding client side validation but it was not very pretty. Thankfully in MVC 3, things have improved and the process is now fairly trivial and thankfully does not involve changing the
Global.asax
as in the previous version.The first step is for your custom validation attribute to implement IClientValidatable. This is a simple, one method interface:
If you run the application now and view source, you will see that the password input html now contains your
notequalto
data attributes:Creating a custom jQuery validate function
All of this code is best to be placed in a separate JavaScript file.
Depending on your validation requirements, you may find that the jquery.validate library already has the code that you need for the validation itself. There are lots of validators in jquery.validate that have not been implemented or mapped to data annotations, so if these fulfil your need, then all you need to write in javascript is an adapter or even a call to a built-in adapter which can be as little as a single line. Take a look inside jquery.validate.js to find out what is available.
Using an existing jquery.validate.unobtrusive adapter
The job of the adapter is to read the HTML5
data-*
attributes on your form element and convert this data into a form that can be understood by jquery.validate and your custom validation function. You are not required to do all the work yourself though and in many cases, you can call a built-in adapter. jquery.validate.unobtrusive declares three built-in adapters which can be used in the majority of situations. These are:If your validator does not fit into one of these categories, you are required to write your own adapter using the
jQuery.validator.unobtrusive.adapters.add
method. This is not as difficulty as it sounds and we'll see an example later in the article.We use the
addSingleVal
method, passing in the name of the adapter and the name of the single value that we want to pass. Should the name of the validation function differ from the adapter, you can pass in a third parameter (ruleName
):At this point, our custom validator is complete.
For better understanding refer to the article itself which presents more description and a more complex example.
HTH.
如果您想全局指定消息而不是为每个项目指定自定义消息,这是纯 js 中的另一个解决方案。
关键是验证消息是使用每个元素上的
data-val-xxx
属性使用jquery.validation.unobtrusive.js
设置的,因此您所要做的就是在库使用它们之前替换这些消息,这有点脏,但我只是想快速完成工作,所以这里进行数字类型验证:好处是它不需要编译,您可以扩展它稍后很容易,虽然不健壮,但速度很快。
Here is another solution in pure js that works if you want to specify messages globally not custom messages for each item.
The key is that validation messages are set using
jquery.validation.unobtrusive.js
using thedata-val-xxx
attribute on each element, so all you have to do is to replace those messages before the library uses them, it is a bit dirty but I just wanted to get the work done and fast, so here it goes for number type validation:the good thing is that it does not require compiling and you can extend it easily later, not robust though, but fast.
您可以将
ClientDataTypeModelValidatorProvider
类的ResourceKey
设置为包含FieldMustBeNumeric
键的全局资源的名称,以将数字的 MVC 验证错误消息替换为您的自定义消息。日期验证错误消息的键也是FieldMustBeDate
。请参阅
You can set
ResourceKey
ofClientDataTypeModelValidatorProvider
class to name of a global resource that containsFieldMustBeNumeric
key to replace MVC validation error message of number with your custom message. Also key of date validation error message isFieldMustBeDate
.See here for more details on how to add the
MyResources.resx
file to your project:这是另一个解决方案,它更改消息客户端而不更改 MVC3 源。此博文中的完整详细信息:
https://greenicicle.wordpress.com/2011/02/28/fixing-non-localized-validation-messages-with-javascript/
简而言之,您需要什么要做的就是在加载 jQuery 验证后包含以下脚本以及 适当的本地化文件。
Here is another solution which changes the message client side without changed MVC3 source. Full details in this blog post:
https://greenicicle.wordpress.com/2011/02/28/fixing-non-localizable-validation-messages-with-javascript/
In short what you need to do is include the following script after jQuery validation is loaded plus the appropriate localisation file.
来自我拥有的这本关于 MVC 3 的书。您所要做的就是:
注意如何生成 ErrorMessage,指定当前区域性,并从 ValidationMessages(这里是区域性细节).resx 资源文件中提取本地化消息。如果您不需要,只需将其替换为您自己的消息即可。
From this book on MVC 3 that I have. All you have to do is this:
Notice how the ErrorMessage is yielded, you specify the current culture and the localized message is extracted from the ValidationMessages(here be culture specifics).resx resource file. If you don't need that, just replace it with your own message.
作为解决此问题的另一种方法,我应用了正则表达式属性来捕获无效条目并在那里设置我的消息:
这有点黑客,但这似乎比其他解决方案所呈现的复杂性更可取,至少在我的特定情况下。
编辑:这在 MVC3 中运行良好,但似乎 MVC4+ 可能有更好的解决方案。
As an alternate way around this, I applied a RegularExpression attribute to catch the invalid entry and set my message there:
This slightly a hack but this seemed preferable to the complexity the other solutions presented, at least in my particular situation.
EDIT: This worked well in MVC3 but it seems that there may well be better solutions for MVC4+.
这并不容易。默认消息作为嵌入资源存储到 System.Web.Mvc 程序集中,并且获取的方法是内部密封内部类 (System.Web.Mvc .ClientDataTypeModelValidatorProvider+NumericModelValidator.MakeErrorString)。就好像微软编码的那个人隐藏了一个绝密:-)
你可以看看下面的博客文章 描述了一种可能的解决方案。您基本上需要将现有的 ClientDataTypeModelValidatorProvider 替换为定制的。
如果您不喜欢需要执行的硬核编码,您还可以用字符串替换视图模型中的这个整数值,并在其上添加一个自定义验证属性,该属性将进行解析并提供自定义错误消息(甚至可以本地化)。
This is not gonna be easy. The default message is stored as an embedded resource into the
System.Web.Mvc
assembly and the method that is fetching is a private static method of an internal sealed inner class (System.Web.Mvc.ClientDataTypeModelValidatorProvider+NumericModelValidator.MakeErrorString
). It's as if the guy at Microsoft coding this was hiding a top secret :-)You may take a look at the following blog post which describes a possible solution. You basically need to replace the existing ClientDataTypeModelValidatorProvider with a custom one.
If you don't like the hardcore coding that you will need to do you could also replace this integer value inside your view model with a string and have a custom validation attribute on it which would do the parsing and provide a custom error message (which could even be localized).
您需要做的是:
在
Global.asax
的Application_Start()
中添加以下代码:右键单击 VS 中的 ASP.NET MVC 项目。选择
添加=>添加 ASP.NET 文件夹 => App_GlobalResources
。在该文件夹中添加一个名为
Messages.resx
的.resx
文件。在
.resx
文件中添加这些字符串资源:根据需要更改
FieldMustBeNumeric
值...:)就完成了。
查看此帖子了解更多详细信息:
本地化 ASP.NET MVC 和 WebForms 中的默认错误消息
What you have to do is:
Add the following code inside
Application_Start()
inGlobal.asax
:Right click your ASP.NET MVC project in VS. Select
Add => Add ASP.NET Folder => App_GlobalResources
.Add a
.resx
file calledMessages.resx
in that folder.Add these string resources in the
.resx
file:Change the
FieldMustBeNumeric
value as you want... :)You're done.
Check this post for more details:
Localizing Default Error Messages in ASP.NET MVC and WebForms
您可以通过在呈现字段时自行提供 data-val-number 属性来覆盖该消息。这会覆盖默认消息。这至少适用于 MVC 4。
请记住,您必须在属性名称中使用下划线,Razor 才能接受您的属性。
You can override the message by supplying the data-val-number attribute yourself when rendering the field. This overrides the default message. This works at least with MVC 4.
Remember that you have to use underscore in the attribute name for Razor to accept your attribute.