如何更改默认"字段必须是数字"

Bil*_*ill 7 jquery asp.net-mvc-3

我正在研究MVC 3应用程序.模型中的一个字段是double类型,定义如下:

    [Required(ErrorMessageResourceName = "ListingItemPriceRequired", ErrorMessageResourceType = typeof(ErrorMessages))]
    [Display(Name = "DisplayListingItemPrice", ResourceType = typeof(Display))]
    [Range(1, 500000000, ErrorMessageResourceName = "ListingItemPriceNotWithinRange", ErrorMessageResourceType = typeof(ErrorMessages))]
    public double Price { get; set; }
Run Code Online (Sandbox Code Playgroud)

但是,当我输入带有一些尾随空格(如"342")的数字值时,我会收到默认消息"字段价格必须是数字".

甚至价格输入字段上的验证属性也有"data-val-number".

谢谢

Sco*_*ttE 15

如果您只需更改不显眼的验证方面,您可以随时提供自己的jquery验证属性:

@Html.TextBoxFor(model => model.Price, new Dictionary<string, object>() { { "data-val-number", "Price must be a valid number." } })
Run Code Online (Sandbox Code Playgroud)

或者,以下更简单,因为MVC用属性名称中的短划线替换下划线:

@Html.TextBoxFor(model => model.Price, new { data_val_number = "Price must be a valid number." })
Run Code Online (Sandbox Code Playgroud)


Nic*_*ick 6

我发现更容易说:

 [RegularExpression("([0-9]+)", ErrorMessageResourceType = typeof(ErrorMessage), ErrorMessageResourceName = "NumberInvalid")]
Run Code Online (Sandbox Code Playgroud)


Dar*_*rov 5

默认消息作为字符串资源深入到框架中。当尝试将字符串值绑定到双精度类型时,它由默认模型绑定器添加。因此,如果您想更改此默认消息,您可以编写自定义模型绑定器。这是我为具有相同问题的 DateTime 类型编写的示例:https : //stackoverflow.com/a/7836093/29407

  • 我实现了一个自定义模型绑定器,但仍然在客户端,显示相同的句子,默认的。如何在客户端注入另一条消息?谢谢 (3认同)