剑道数字文本框的范围验证不采用默认消息



剑道数字文本框的范围验证,即使已指定自定义消息,也不会显示自定义消息。

Range数据注释是这样定义的。

[Required(ErrorMessage = "Enter length")]
[Range(1, 10, ErrorMessageName = "{0} should be from {1} to {2}")]
public int Length { get; set; }

剃刀标记是,

@Html.Kendo().NumericTextBoxFor(m => m.Length)

但是,验证消息仍显示为,

请输入一个小于或等于 10 的值。

而不是

长度应为 1 到 10。


本问题仅供参考。

这个问题已经在这里问过了。剑道数字文本框范围验证器消息

但是由于同样没有公认的答案,甚至答案也不是解释性的,所以我会在这里添加答案。

此问题是因为 Kendo 会覆盖文本框的输入类型,并且还为 Kendo 验证器添加不同的消息,该消息是 Kendo 覆盖,用于不引人注目的验证,即使您没有使用它。

为了解决这个问题,并实现通用Range属性,我必须设置自定义属性并将其注册为Range适配器。

在global.asax中,

DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(RangeAttribute),
typeof(CustomRangeAttributeAdapter));

我必须在我的自定义验证命名空间中定义这样的CustomRangeAttributeAdapter

public class CustomRangeAttributeAdapter : RangeAttributeAdapter
{
public CustomRangeAttributeAdapter(ModelMetadata metadata,
ControllerContext context,
RangeAttribute attribute)
: base(metadata, context, attribute)
{
attribute.ErrorMessageResourceName = <Resource_Name_Here>;
attribute.ErrorMessageResourceType = typeof(<Resource_File_Name>);
metadata.DataTypeName = DataType.Currency.ToString();
}
} 

我必须设置DataType以确保它不采用默认类型。在此之后,您可以按原样使用Range属性。如果需要显示自定义消息,请对ErrorMessageErrorMessageName执行空检查。

最新更新