如何在由@Html helper生成的MVC中更改“data- var -number”消息验证

时间:2021-06-28 16:11:43

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:

将这个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.

我想要自定义数据-值-值错误消息,我猜它是生成的,因为百分比更改是一个整数。我在寻找这样一个属性来改变它,范围或任何相关的东西都不起作用。我知道在编辑unobtrusive的js文件本身或在客户端重写它是有可能的。我想像服务器端中的其他人一样更改数据值号的错误消息。

13 个解决方案

#1


36  

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 :-)

这并不容易。默认消息作为嵌入式资源存储到System.Web中。Mvc组装和正在获取的方法是一个内部密封的内部类(system . web .Mvc. client . clientdatatypemodelvalidatorprovider +NumericModelValidator.MakeErrorString)的私有静态方法。就好像微软编码的那个家伙在隐藏一个最高机密:-)

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.

您可以看看下面的博客文章,它描述了一种可能的解决方案。您基本上需要用一个自定义的ClientDataTypeModelValidatorProvider替换现有的ClientDataTypeModelValidatorProvider。

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).

如果你不喜欢的核心编码需要你也可以取代这个整数值在你的视图模型和一个字符串有一个自定义验证属性将进行解析并提供一个自定义的错误消息(甚至可以本地化)。

#2


68  

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.

您可以在呈现字段时自己提供data- var -number属性来覆盖消息。这将覆盖默认消息。这至少适用于MVC 4。

@Html.EditorFor(model => model.MyNumberField, new { data_val_number="Supply an integer, dude!" })

@Html。EditorFor(模型= >模型。MyNumberField, new {data_val_number="提供一个整数,伙计!"})

Remember that you have to use underscore in the attribute name for Razor to accept your attribute.

记住,必须在Razor的属性名中使用下划线来接受属性。

#3


49  

What you have to do is:

你要做的是:

Add the following code inside Application_Start() in Global.asax:

在Global.asax的Application_Start()中添加以下代码:

 ClientDataTypeModelValidatorProvider.ResourceClassKey = "Messages";
 DefaultModelBinder.ResourceClassKey = "Messages";

Right click your ASP.NET MVC project in VS. Select Add => Add ASP.NET Folder => App_GlobalResources.

右击你的ASP。NET MVC项目在VS. Select Add =>添加ASP。= >包含网络文件夹。

Add a .resx file called Messages.resx in that folder.

添加名为message的.resx文件。resx的文件夹。

Add these string resources in the .resx file:

在.resx文件中添加这些字符串资源:

FieldMustBeDate        The field {0} must be a date.
FieldMustBeNumeric     The field {0} must be a number.
PropertyValueInvalid   The value '{0}' is not valid for {1}.
PropertyValueRequired  A value is required.

Change the FieldMustBeNumeric value as you want... :)

根据需要更改FieldMustBeNumeric值…:)

You're done.

你就完成了。


Check this post for more details:

详情请参阅这篇文章:

Localizing Default Error Messages in ASP.NET MVC and WebForms

在ASP中定位默认错误消息。净MVC和WebForms

#4


22  

As an alternate way around this, I applied a RegularExpression attribute to catch the invalid entry and set my message there:

为了解决这个问题,我使用了一个RegularExpression属性来捕获无效的条目,并在那里设置我的消息:

[RegularExpression(@"[0-9]*$", ErrorMessage = "Please enter a valid number ")]

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+.

编辑:这在MVC3中工作得很好,但是似乎有更好的MVC4+解决方案。

#5


11  

From this book on MVC 3 that I have. All you have to do is this:

我有一本关于MVC 3的书。你所要做的就是:

public class ClientNumberValidatorProvider : ClientDataTypeModelValidatorProvider 
{ 
   public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, 
                                                          ControllerContext context) 
   { 
       bool isNumericField = base.GetValidators(metadata, context).Any(); 
       if (isNumericField) 
           yield return new ClientSideNumberValidator(metadata, context); 
   } 
} 

public class ClientSideNumberValidator : ModelValidator 
{ 
  public ClientSideNumberValidator(ModelMetadata metadata,  
      ControllerContext controllerContext) : base(metadata, controllerContext) { } 

  public override IEnumerable<ModelValidationResult> Validate(object container) 
  { 
     yield break; // Do nothing for server-side validation 
  } 

  public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() 
  { 
     yield return new ModelClientValidationRule { 
        ValidationType = "number", 
        ErrorMessage = string.Format(CultureInfo.CurrentCulture,  
                                     ValidationMessages.MustBeNumber,  
                                     Metadata.GetDisplayName()) 
        }; 
  } 
} 

protected void Application_Start() 
{ 
    // Leave the rest of this method unchanged 

    var existingProvider = ModelValidatorProviders.Providers 
        .Single(x => x is ClientDataTypeModelValidatorProvider); 
    ModelValidatorProviders.Providers.Remove(existingProvider); 
    ModelValidatorProviders.Providers.Add(new ClientNumberValidatorProvider()); 
} 

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.

请注意ErrorMessage是如何产生的,您指定了当前的区域性,并从validationmessage中提取了本地化消息(这里是文化细节)。resx文件资源。如果你不需要,就用你自己的信息替换它。

#6


7  

Here is another solution which changes the message client side without changed MVC3 source. Full details in this blog post:

下面是另一个解决方案,它在不更改MVC3源的情况下更改消息客户端。完整的细节在这篇博文:

https://greenicicle.wordpress.com/2011/02/28/fixing-non-localizable-validation-messages-with-javascript/

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.

简而言之,您需要做的是在加载jQuery验证和适当的本地化文件之后包含以下脚本。

(function ($) {
    // Walk through the adapters that connect unobstrusive validation to jQuery.validate.
    // Look for all adapters that perform number validation
    $.each($.validator.unobtrusive.adapters, function () {
        if (this.name === "number") {
            // Get the method called by the adapter, and replace it with one 
            // that changes the message to the jQuery.validate default message
            // that can be globalized. If that string contains a {0} placeholder, 
            // it is replaced by the field name.
            var baseAdapt = this.adapt;
            this.adapt = function (options) {
                var fieldName = new RegExp("The field (.+) must be a number").exec(options.message)[1];
                options.message = $.validator.format($.validator.messages.number, fieldName);
                baseAdapt(options);
            };
        }
    });
} (jQuery));

#7


4  

You can set ResourceKey of ClientDataTypeModelValidatorProvider class to name of a global resource that contains FieldMustBeNumeric key to replace mvc validation error message of number with your custom message. Also key of date validation error message is FieldMustBeDate.

您可以将ClientDataTypeModelValidatorProvider类的ResourceKey设置为包含FieldMustBeNumeric键的全局资源的名称,以用自定义消息替换mvc验证错误消息。另外,日期验证错误消息的关键是FieldMustBeDate。

ClientDataTypeModelValidatorProvider.ResourceKey="MyResources"; // MyResource is my global resource

#8


3  

Here is another solution in pure js that works if you want to specify messages globally not custom messages for each item.

如果您希望为每个条目指定全局消息而不是自定义消息,那么这是纯js中的另一个解决方案。

The key is that validation messages are set using jquery.validation.unobtrusive.js using the data-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:

关键是使用jquery. valid.unobtrusive设置验证消息。js在每个元素上都使用data- var -xxx属性,所以你所要做的就是在库使用这些消息之前替换它们,这有点麻烦,但我只是想尽快完成工作,这里是数字类型验证:

    $('[data-val-number]').each(function () {
    var el = $(this);
    var orig = el.data('val-number');

    var fieldName = orig.replace('The field ', '');
    fieldName = fieldName.replace(' must be a number.', '');

    el.attr('data-val-number', fieldName + ' باید عددی باشد')
});

the good thing is that it does not require compiling and you can extend it easily later, not robust though, but fast.

好处是,它不需要编译,您可以稍后轻松地扩展它,虽然不是健壮的,但是很快。

#9


2  

Check this out too:

看看这个:

The Complete Guide To Validation In ASP.NET MVC 3 - Part 2

在ASP中完整的验证指南。NET MVC 3 -第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 implement IClientValidatable on our attribute to allow HTML5 data-* 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.

创建在客户端和服务器上都能运行的全功能自定义验证器有四个不同的部分。首先,我们对ValidationAttribute进行子类化,并添加服务器端验证逻辑。接下来,我们在属性上实现IClientValidatable,以允许将HTML5数据-*属性传递给客户端。第三,我们编写一个自定义JavaScript函数,它对客户端执行验证。最后,我们创建一个适配器,将HTML5属性转换为我们的自定义函数可以理解的格式。虽然这听起来像很多工作,但一旦你开始,你会发现它相对简单。

Subclassing ValidationAttribute

子类化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.

在本例中,我们将编写一个NotEqualTo validator,它只检查一个属性的值是否与另一个属性的值相等。

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class NotEqualToAttribute : ValidationAttribute
{
    private const string DefaultErrorMessage = "{0} cannot be the same as {1}.";

    public string OtherProperty { get; private set; }

    public NotEqualToAttribute(string otherProperty)
        : base(DefaultErrorMessage)
    {
        if (string.IsNullOrEmpty(otherProperty))
        {
            throw new ArgumentNullException("otherProperty");
        }

        OtherProperty = otherProperty;
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(ErrorMessageString, name, OtherProperty);
    }

    protected override ValidationResult IsValid(object value, 
        ValidationContext validationContext)
    {
        if (value != null)
        {
            var otherProperty = validationContext.ObjectInstance.GetType()
                .GetProperty(OtherProperty);

            var otherPropertyValue = otherProperty
                .GetValue(validationContext.ObjectInstance, null);

            if (value.Equals(otherPropertyValue))
            {
                return new ValidationResult(
                    FormatErrorMessage(validationContext.DisplayName));
            }
        }
    return ValidationResult.Success;
    }        
}

Add the new attribute to the password property of the RegisterModel and run the application.

将新属性添加到RegisterModel的密码属性并运行应用程序。

[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
[NotEqualTo("UserName")]
public string Password { get; set; }
...

Implementing IClientValidatable

实现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.

ASP。NET MVC 2有一种添加客户端验证的机制,但不是很好。值得庆幸的是,在MVC 3中,事情已经得到了改善,而且这个过程现在非常简单,而且还不需要改变全局。asax和之前的版本一样。

The first step is for your custom validation attribute to implement IClientValidatable. This is a simple, one method interface:

第一步是让自定义验证属性实现IClientValidatable。这是一个简单的方法接口:

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
    ModelMetadata metadata,
    ControllerContext context)
{
    var clientValidationRule = new ModelClientValidationRule()
    {
        ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
        ValidationType = "notequalto"
    };

    clientValidationRule.ValidationParameters.Add("otherproperty", OtherProperty);

    return new[] { clientValidationRule };
}

If you run the application now and view source, you will see that the password input html now contains your notequalto data attributes:

如果您现在运行应用程序并查看源代码,您将看到密码输入html现在包含您的notequalto数据属性:

<div class="editor-field">
    <input data-val="true" data-val-notequalto="Password cannot be the same as UserName." 
    data-val-notequalto-otherproperty="UserName" 
    data-val-regex="Weak password detected." 
    data-val-regex-pattern="^(?!password$)(?!12345$).*" 
    data-val-required="The Password field is required." 
    id="Password" name="Password" type="password" />
    <span class="hint">Enter your password here</span>
    <span class="field-validation-valid" data-valmsg-for="Password" 
    data-valmsg-replace="true"></span>
</div>

Creating a custom jQuery validate function

创建自定义jQuery验证函数

All of this code is best to be placed in a separate JavaScript file.

所有这些代码最好放在一个单独的JavaScript文件中。

(function ($) {
    $.validator.addMethod("notequalto", function (value, element, params) {
        if (!this.optional(element)) {
            var otherProp = $('#' + params);
            return (otherProp.val() != 
        }
    return true;
});

$.validator.unobtrusive.adapters.addSingleVal("notequalto", "otherproperty");

}(jQuery));

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.

根据您的验证需求,您可能会发现jquery。验证库已经拥有验证本身所需的代码。jquery中有很多验证器。验证没有实现或映射到数据注释,因此如果这些实现了您的需求,那么您在javascript中需要编写的就是一个适配器,甚至是对一个内置适配器的调用,这个适配器的调用可能只需要一行代码。查看一下jquery.validate。要找出什么是可用的。

Using an existing jquery.validate.unobtrusive adapter

使用现有jquery.validate。不引人注目的适配器

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:

适配器的任务是读取表单元素上的HTML5 data-*属性,并将这些数据转换为可以被jquery理解的表单。验证和自定义验证函数。您不必自己完成所有的工作,在许多情况下,您可以调用内置适配器。jquery.validate。unobtrusive声明了三个内置的适配器,它们可以在大多数情况下使用。这些都是:

jQuery.validator.unobtrusive.adapters.addBool - used when your validator does not need any additional data.
jQuery.validator.unobtrusive.adapters.addSingleVal - used when your validator takes in one piece of additional data.
jQuery.validator.unobtrusive.adapters.addMinMax - used when your validator deals with minimum and maximum values such as range or string length.

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.

如果您的验证器不适合这些类别之一,则需要使用jquery .validator.unobtrusi .adapter编写您自己的适配器。添加方法。这并不像听起来那么困难,我们将在本文后面看到一个示例。

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):

我们使用addSingleVal方法,传入适配器的名称和我们想要传递的单个值的名称。如果验证函数的名称与适配器不同,您可以传入第三个参数(规则名):

jQuery.validator.unobtrusive.adapters.addSingleVal("notequalto", "otherproperty", "mynotequaltofunction");

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.

HTH。

#10


1  

I just did this and then used a regex expression:

我只是这样做了,然后使用regex表达式:

$(document).ready(function () {
    $.validator.methods.number = function (e) {
        return true;
    };
});


[RegularExpression(@"^[0-9\.]*$", ErrorMessage = "Invalid Amount")]
public decimal? Amount { get; set; }

#11


1  

Or you can simply do this.

或者你可以这么做。

@Html.ValidationMessageFor(m => m.PercentChange, "Custom Message: Input value must be a number"), new { @style = "display:none" })

Hope this helps.

希望这个有帮助。

#12


0  

I have this problem in KendoGrid, I use a script at the END of View to override data-val-number:

我在KendoGrid中有这个问题,我在视图的末尾使用一个脚本覆盖数据值-number:

@(Html.Kendo().Grid<Test.ViewModel>(Model)
  .Name("listado")
  ...
  .Columns(columns =>
    {
        columns.Bound("idElementColumn").Filterable(false);
    ...
    }

And at least, in the end of View I put:

至少,在我最后的观点中

<script type="text/javascript">
        $("#listado").on("click", function (e) {
            $(".k-grid #idElementColumn").attr('data-val-number', 'Ingrese un número.');
        });    
</script>

#13


0  

I make this putting this on my view

我把这个放到我的视图上

@Html.DropDownListFor(m => m.BenefNamePos, Model.Options, new { onchange = "changePosition(this);", @class="form-control", data_val_number = "This is my custom message" })

#1


36  

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 :-)

这并不容易。默认消息作为嵌入式资源存储到System.Web中。Mvc组装和正在获取的方法是一个内部密封的内部类(system . web .Mvc. client . clientdatatypemodelvalidatorprovider +NumericModelValidator.MakeErrorString)的私有静态方法。就好像微软编码的那个家伙在隐藏一个最高机密:-)

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.

您可以看看下面的博客文章,它描述了一种可能的解决方案。您基本上需要用一个自定义的ClientDataTypeModelValidatorProvider替换现有的ClientDataTypeModelValidatorProvider。

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).

如果你不喜欢的核心编码需要你也可以取代这个整数值在你的视图模型和一个字符串有一个自定义验证属性将进行解析并提供一个自定义的错误消息(甚至可以本地化)。

#2


68  

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.

您可以在呈现字段时自己提供data- var -number属性来覆盖消息。这将覆盖默认消息。这至少适用于MVC 4。

@Html.EditorFor(model => model.MyNumberField, new { data_val_number="Supply an integer, dude!" })

@Html。EditorFor(模型= >模型。MyNumberField, new {data_val_number="提供一个整数,伙计!"})

Remember that you have to use underscore in the attribute name for Razor to accept your attribute.

记住,必须在Razor的属性名中使用下划线来接受属性。

#3


49  

What you have to do is:

你要做的是:

Add the following code inside Application_Start() in Global.asax:

在Global.asax的Application_Start()中添加以下代码:

 ClientDataTypeModelValidatorProvider.ResourceClassKey = "Messages";
 DefaultModelBinder.ResourceClassKey = "Messages";

Right click your ASP.NET MVC project in VS. Select Add => Add ASP.NET Folder => App_GlobalResources.

右击你的ASP。NET MVC项目在VS. Select Add =>添加ASP。= >包含网络文件夹。

Add a .resx file called Messages.resx in that folder.

添加名为message的.resx文件。resx的文件夹。

Add these string resources in the .resx file:

在.resx文件中添加这些字符串资源:

FieldMustBeDate        The field {0} must be a date.
FieldMustBeNumeric     The field {0} must be a number.
PropertyValueInvalid   The value '{0}' is not valid for {1}.
PropertyValueRequired  A value is required.

Change the FieldMustBeNumeric value as you want... :)

根据需要更改FieldMustBeNumeric值…:)

You're done.

你就完成了。


Check this post for more details:

详情请参阅这篇文章:

Localizing Default Error Messages in ASP.NET MVC and WebForms

在ASP中定位默认错误消息。净MVC和WebForms

#4


22  

As an alternate way around this, I applied a RegularExpression attribute to catch the invalid entry and set my message there:

为了解决这个问题,我使用了一个RegularExpression属性来捕获无效的条目,并在那里设置我的消息:

[RegularExpression(@"[0-9]*$", ErrorMessage = "Please enter a valid number ")]

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+.

编辑:这在MVC3中工作得很好,但是似乎有更好的MVC4+解决方案。

#5


11  

From this book on MVC 3 that I have. All you have to do is this:

我有一本关于MVC 3的书。你所要做的就是:

public class ClientNumberValidatorProvider : ClientDataTypeModelValidatorProvider 
{ 
   public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, 
                                                          ControllerContext context) 
   { 
       bool isNumericField = base.GetValidators(metadata, context).Any(); 
       if (isNumericField) 
           yield return new ClientSideNumberValidator(metadata, context); 
   } 
} 

public class ClientSideNumberValidator : ModelValidator 
{ 
  public ClientSideNumberValidator(ModelMetadata metadata,  
      ControllerContext controllerContext) : base(metadata, controllerContext) { } 

  public override IEnumerable<ModelValidationResult> Validate(object container) 
  { 
     yield break; // Do nothing for server-side validation 
  } 

  public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() 
  { 
     yield return new ModelClientValidationRule { 
        ValidationType = "number", 
        ErrorMessage = string.Format(CultureInfo.CurrentCulture,  
                                     ValidationMessages.MustBeNumber,  
                                     Metadata.GetDisplayName()) 
        }; 
  } 
} 

protected void Application_Start() 
{ 
    // Leave the rest of this method unchanged 

    var existingProvider = ModelValidatorProviders.Providers 
        .Single(x => x is ClientDataTypeModelValidatorProvider); 
    ModelValidatorProviders.Providers.Remove(existingProvider); 
    ModelValidatorProviders.Providers.Add(new ClientNumberValidatorProvider()); 
} 

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.

请注意ErrorMessage是如何产生的,您指定了当前的区域性,并从validationmessage中提取了本地化消息(这里是文化细节)。resx文件资源。如果你不需要,就用你自己的信息替换它。

#6


7  

Here is another solution which changes the message client side without changed MVC3 source. Full details in this blog post:

下面是另一个解决方案,它在不更改MVC3源的情况下更改消息客户端。完整的细节在这篇博文:

https://greenicicle.wordpress.com/2011/02/28/fixing-non-localizable-validation-messages-with-javascript/

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.

简而言之,您需要做的是在加载jQuery验证和适当的本地化文件之后包含以下脚本。

(function ($) {
    // Walk through the adapters that connect unobstrusive validation to jQuery.validate.
    // Look for all adapters that perform number validation
    $.each($.validator.unobtrusive.adapters, function () {
        if (this.name === "number") {
            // Get the method called by the adapter, and replace it with one 
            // that changes the message to the jQuery.validate default message
            // that can be globalized. If that string contains a {0} placeholder, 
            // it is replaced by the field name.
            var baseAdapt = this.adapt;
            this.adapt = function (options) {
                var fieldName = new RegExp("The field (.+) must be a number").exec(options.message)[1];
                options.message = $.validator.format($.validator.messages.number, fieldName);
                baseAdapt(options);
            };
        }
    });
} (jQuery));

#7


4  

You can set ResourceKey of ClientDataTypeModelValidatorProvider class to name of a global resource that contains FieldMustBeNumeric key to replace mvc validation error message of number with your custom message. Also key of date validation error message is FieldMustBeDate.

您可以将ClientDataTypeModelValidatorProvider类的ResourceKey设置为包含FieldMustBeNumeric键的全局资源的名称,以用自定义消息替换mvc验证错误消息。另外,日期验证错误消息的关键是FieldMustBeDate。

ClientDataTypeModelValidatorProvider.ResourceKey="MyResources"; // MyResource is my global resource

#8


3  

Here is another solution in pure js that works if you want to specify messages globally not custom messages for each item.

如果您希望为每个条目指定全局消息而不是自定义消息,那么这是纯js中的另一个解决方案。

The key is that validation messages are set using jquery.validation.unobtrusive.js using the data-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:

关键是使用jquery. valid.unobtrusive设置验证消息。js在每个元素上都使用data- var -xxx属性,所以你所要做的就是在库使用这些消息之前替换它们,这有点麻烦,但我只是想尽快完成工作,这里是数字类型验证:

    $('[data-val-number]').each(function () {
    var el = $(this);
    var orig = el.data('val-number');

    var fieldName = orig.replace('The field ', '');
    fieldName = fieldName.replace(' must be a number.', '');

    el.attr('data-val-number', fieldName + ' باید عددی باشد')
});

the good thing is that it does not require compiling and you can extend it easily later, not robust though, but fast.

好处是,它不需要编译,您可以稍后轻松地扩展它,虽然不是健壮的,但是很快。

#9


2  

Check this out too:

看看这个:

The Complete Guide To Validation In ASP.NET MVC 3 - Part 2

在ASP中完整的验证指南。NET MVC 3 -第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 implement IClientValidatable on our attribute to allow HTML5 data-* 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.

创建在客户端和服务器上都能运行的全功能自定义验证器有四个不同的部分。首先,我们对ValidationAttribute进行子类化,并添加服务器端验证逻辑。接下来,我们在属性上实现IClientValidatable,以允许将HTML5数据-*属性传递给客户端。第三,我们编写一个自定义JavaScript函数,它对客户端执行验证。最后,我们创建一个适配器,将HTML5属性转换为我们的自定义函数可以理解的格式。虽然这听起来像很多工作,但一旦你开始,你会发现它相对简单。

Subclassing ValidationAttribute

子类化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.

在本例中,我们将编写一个NotEqualTo validator,它只检查一个属性的值是否与另一个属性的值相等。

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class NotEqualToAttribute : ValidationAttribute
{
    private const string DefaultErrorMessage = "{0} cannot be the same as {1}.";

    public string OtherProperty { get; private set; }

    public NotEqualToAttribute(string otherProperty)
        : base(DefaultErrorMessage)
    {
        if (string.IsNullOrEmpty(otherProperty))
        {
            throw new ArgumentNullException("otherProperty");
        }

        OtherProperty = otherProperty;
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(ErrorMessageString, name, OtherProperty);
    }

    protected override ValidationResult IsValid(object value, 
        ValidationContext validationContext)
    {
        if (value != null)
        {
            var otherProperty = validationContext.ObjectInstance.GetType()
                .GetProperty(OtherProperty);

            var otherPropertyValue = otherProperty
                .GetValue(validationContext.ObjectInstance, null);

            if (value.Equals(otherPropertyValue))
            {
                return new ValidationResult(
                    FormatErrorMessage(validationContext.DisplayName));
            }
        }
    return ValidationResult.Success;
    }        
}

Add the new attribute to the password property of the RegisterModel and run the application.

将新属性添加到RegisterModel的密码属性并运行应用程序。

[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
[NotEqualTo("UserName")]
public string Password { get; set; }
...

Implementing IClientValidatable

实现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.

ASP。NET MVC 2有一种添加客户端验证的机制,但不是很好。值得庆幸的是,在MVC 3中,事情已经得到了改善,而且这个过程现在非常简单,而且还不需要改变全局。asax和之前的版本一样。

The first step is for your custom validation attribute to implement IClientValidatable. This is a simple, one method interface:

第一步是让自定义验证属性实现IClientValidatable。这是一个简单的方法接口:

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
    ModelMetadata metadata,
    ControllerContext context)
{
    var clientValidationRule = new ModelClientValidationRule()
    {
        ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
        ValidationType = "notequalto"
    };

    clientValidationRule.ValidationParameters.Add("otherproperty", OtherProperty);

    return new[] { clientValidationRule };
}

If you run the application now and view source, you will see that the password input html now contains your notequalto data attributes:

如果您现在运行应用程序并查看源代码,您将看到密码输入html现在包含您的notequalto数据属性:

<div class="editor-field">
    <input data-val="true" data-val-notequalto="Password cannot be the same as UserName." 
    data-val-notequalto-otherproperty="UserName" 
    data-val-regex="Weak password detected." 
    data-val-regex-pattern="^(?!password$)(?!12345$).*" 
    data-val-required="The Password field is required." 
    id="Password" name="Password" type="password" />
    <span class="hint">Enter your password here</span>
    <span class="field-validation-valid" data-valmsg-for="Password" 
    data-valmsg-replace="true"></span>
</div>

Creating a custom jQuery validate function

创建自定义jQuery验证函数

All of this code is best to be placed in a separate JavaScript file.

所有这些代码最好放在一个单独的JavaScript文件中。

(function ($) {
    $.validator.addMethod("notequalto", function (value, element, params) {
        if (!this.optional(element)) {
            var otherProp = $('#' + params);
            return (otherProp.val() != 
        }
    return true;
});

$.validator.unobtrusive.adapters.addSingleVal("notequalto", "otherproperty");

}(jQuery));

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.

根据您的验证需求,您可能会发现jquery。验证库已经拥有验证本身所需的代码。jquery中有很多验证器。验证没有实现或映射到数据注释,因此如果这些实现了您的需求,那么您在javascript中需要编写的就是一个适配器,甚至是对一个内置适配器的调用,这个适配器的调用可能只需要一行代码。查看一下jquery.validate。要找出什么是可用的。

Using an existing jquery.validate.unobtrusive adapter

使用现有jquery.validate。不引人注目的适配器

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:

适配器的任务是读取表单元素上的HTML5 data-*属性,并将这些数据转换为可以被jquery理解的表单。验证和自定义验证函数。您不必自己完成所有的工作,在许多情况下,您可以调用内置适配器。jquery.validate。unobtrusive声明了三个内置的适配器,它们可以在大多数情况下使用。这些都是:

jQuery.validator.unobtrusive.adapters.addBool - used when your validator does not need any additional data.
jQuery.validator.unobtrusive.adapters.addSingleVal - used when your validator takes in one piece of additional data.
jQuery.validator.unobtrusive.adapters.addMinMax - used when your validator deals with minimum and maximum values such as range or string length.

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.

如果您的验证器不适合这些类别之一,则需要使用jquery .validator.unobtrusi .adapter编写您自己的适配器。添加方法。这并不像听起来那么困难,我们将在本文后面看到一个示例。

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):

我们使用addSingleVal方法,传入适配器的名称和我们想要传递的单个值的名称。如果验证函数的名称与适配器不同,您可以传入第三个参数(规则名):

jQuery.validator.unobtrusive.adapters.addSingleVal("notequalto", "otherproperty", "mynotequaltofunction");

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.

HTH。

#10


1  

I just did this and then used a regex expression:

我只是这样做了,然后使用regex表达式:

$(document).ready(function () {
    $.validator.methods.number = function (e) {
        return true;
    };
});


[RegularExpression(@"^[0-9\.]*$", ErrorMessage = "Invalid Amount")]
public decimal? Amount { get; set; }

#11


1  

Or you can simply do this.

或者你可以这么做。

@Html.ValidationMessageFor(m => m.PercentChange, "Custom Message: Input value must be a number"), new { @style = "display:none" })

Hope this helps.

希望这个有帮助。

#12


0  

I have this problem in KendoGrid, I use a script at the END of View to override data-val-number:

我在KendoGrid中有这个问题,我在视图的末尾使用一个脚本覆盖数据值-number:

@(Html.Kendo().Grid<Test.ViewModel>(Model)
  .Name("listado")
  ...
  .Columns(columns =>
    {
        columns.Bound("idElementColumn").Filterable(false);
    ...
    }

And at least, in the end of View I put:

至少,在我最后的观点中

<script type="text/javascript">
        $("#listado").on("click", function (e) {
            $(".k-grid #idElementColumn").attr('data-val-number', 'Ingrese un número.');
        });    
</script>

#13


0  

I make this putting this on my view

我把这个放到我的视图上

@Html.DropDownListFor(m => m.BenefNamePos, Model.Options, new { onchange = "changePosition(this);", @class="form-control", data_val_number = "This is my custom message" })