如何更改“数据值编号” MVC 中的消息验证,由 @Html 帮助程序生成

发布于 2024-12-14 17:38:53 字数 848 浏览 2 评论 0原文

假设这个模型:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

过度放纵 2024-12-21 17:39:32

一个简单的方法是,在 ViewModel 上使用 dataannotation 更改消息:

[Required(ErrorMessage ="الزامی")]
[StringLength(maximumLength:50,MinimumLength =2)]
[Display(Name = "نام")]
public string FirstName { get; set; }

a simple method is, use dataanotation change message on ViewModel:

[Required(ErrorMessage ="الزامی")]
[StringLength(maximumLength:50,MinimumLength =2)]
[Display(Name = "نام")]
public string FirstName { get; set; }
我的痛♀有谁懂 2024-12-21 17:39:30

我在 KendoGrid 中遇到这个问题,我在视图末尾使用脚本来覆盖 data-val-number:

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

至少,在视图末尾我放置:

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

I have this problem in KendoGrid, I use a script at the END of View to override data-val-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>
梦情居士 2024-12-21 17:39:25

我把这个放在我的观点上

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

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" })
做个少女永远怀春 2024-12-21 17:39:23

或者你可以简单地这样做。

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

希望这有帮助。

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.

征棹 2024-12-21 17:39:22

我刚刚这样做了,然后使用了正则表达式:

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


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

I just did this and then used a regex expression:

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


[RegularExpression(@"^[0-9\.]*$", ErrorMessage = "Invalid Amount")]
public decimal? Amount { get; set; }
木森分化 2024-12-21 17:39:20

也看看这个:

ASP.NET MVC 3 中的验证完整指南 - 第 2 部分

本文的主要部分如下(复制粘贴)。

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

子类化 ValidationAttribute

在此示例中,我们将编写一个 NotEqualTo 验证器,它仅检查一个属性的值是否不等于另一个属性的值。

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

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

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

实现 IClientValidatable

ASP.NET MVC 2 有一个添加客户端验证的机制,但它不是很漂亮。值得庆幸的是,在 MVC 3 中,情况有所改善,该过程现在相当简单,而且幸运的是,涉及到像以前版本中那样更改 Global.asax

第一步是让您的自定义验证属性实现 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 };
}

如果您现在运行应用程序并查看源代码,您将看到密码输入 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>

创建自定义 jQuery 验证函数

所有这些代码最好放置在单独的 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));

根据您的验证要求,您可能会发现 jquery.validate 库已经具有验证本身所需的代码。 jquery.validate 中有很多验证器尚未实现或映射到数据注释,因此如果这些验证器满足您的需求,那么您需要在 javascript 中编写的只是一个适配器,甚至是对内置适配器的调用,它可以只需一行即可。查看jquery.validate.js内部以了解可用的内容。

使用现有的 jquery.validate.unobtrusive 适配器

适配器的工作是读取表单元素上的 HTML5 data-* 属性,并将此数据转换为可以可以通过 jquery.validate 和您的自定义验证函数来理解。不过,您不需要自己完成所有工作,在许多情况下,您可以调用内置适配器。 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.

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

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

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

至此,我们的自定义验证器就完成了。

为了更好地理解,请参阅 文章本身提供了更多描述和更复杂的示例。

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

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.

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

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

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:

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:

<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

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

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

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:

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.

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

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.

深居我梦 2024-12-21 17:39:19

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

关键是验证消息是使用每个元素上的 data-val-xxx 属性使用 jquery.validation.unobtrusive.js 设置的,因此您所要做的就是在库使用它们之前替换这些消息,这有点脏,但我只是想快速完成工作,所以这里进行数字类型验证:

    $('[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 + ' باید عددی باشد')
});

好处是它不需要编译,您可以扩展它稍后很容易,虽然不健壮,但速度很快。

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

    $('[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.

那请放手 2024-12-21 17:39:17

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

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

请参阅

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="MyResources"; // MyResource is my global resource

See here for more details on how to add the MyResources.resx file to your project:

烟燃烟灭 2024-12-21 17:39:16

这是另一个解决方案,它更改消息客户端而不更改 MVC3 源。此博文中的完整详细信息:

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

简而言之,您需要什么要做的就是在加载 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));

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.

(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));
陈甜 2024-12-21 17:39:14

来自我拥有的这本关于 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()); 
} 

注意如何生成 ErrorMessage,指定当前区域性,并从 ValidationMessages(这里是区域性细节).resx 资源文件中提取本地化消息。如果您不需要,只需将其替换为您自己的消息即可。

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

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.

永言不败 2024-12-21 17:39:12

作为解决此问题的另一种方法,我应用了正则表达式属性来捕获无效条目并在那里设置我的消息:

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

这有点黑客,但这似乎比其他解决方案所呈现的复杂性更可取,至少在我的特定情况下。

编辑:这在 MVC3 中运行良好,但似乎 MVC4+ 可能有更好的解决方案。

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

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

宛菡 2024-12-21 17:39:10

这并不容易。默认消息作为嵌入资源存储到 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).

兔小萌 2024-12-21 17:39:08

您需要做的是:

Global.asaxApplication_Start() 中添加以下代码:

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

右键单击​​ VS 中的 ASP.NET MVC 项目。选择添加=>添加 ASP.NET 文件夹 => App_GlobalResources

在该文件夹中添加一个名为 Messages.resx.resx 文件。

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

根据需要更改 FieldMustBeNumeric 值...:)

就完成了。


查看此帖子了解更多详细信息:

本地化 ASP.NET MVC 和 WebForms 中的默认错误消息

What you have to do is:

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

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

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

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

Add these string resources in the .resx file:

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

You're done.


Check this post for more details:

Localizing Default Error Messages in ASP.NET MVC and WebForms

水晶透心 2024-12-21 17:39:05

您可以通过在呈现字段时自行提供 data-val-number 属性来覆盖该消息。这会覆盖默认消息。这至少适用于 MVC 4。

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

请记住,您必须在属性名称中使用下划线,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.

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文