Range validation for Kendo numeric Textbox, is not displaying custom message even when the same has been specified.
Range
data annotation is defined like this.
[Required(ErrorMessage = "Enter length")]
[Range(1, 10, ErrorMessageName = "{0} should be from {1} to {2}")]
public int Length { get; set; }
Razor markup is,
@Html.Kendo().NumericTextBoxFor(m => m.Length)
But still, the validation message is displayed as,
Please enter a value less than or equal to 10.
instead of,
Length should be from 1 to 10.
This question is for reference only.
This question has been asked here already. Kendo numeric textbox range validator message
But since the same has no accepted answer and even the answers were not explanatory, I would be adding answer here.
This issue is because Kendo overrides the input type of the textbox and also adds different message for Kendo validator which is Kendo overlay for unobtrusive validation, even if you are not using it.
To resolve this, and to implement generic Range
attribute I had to set up custom attribute and register it as Range
adapter.
in global.asax,
DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(RangeAttribute),
typeof(CustomRangeAttributeAdapter));
I had to define CustomRangeAttributeAdapter
like this in my custom validation namespace,
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();
}
}
I had to set the DataType
to make sure it does not take default type. After this you can use Range
attribute as it is. If you need to display custom defined messages, then do the null check for the ErrorMessage
and ErrorMessageName
.