The default StringLength validation error message is too long for my purposes, so I would like to make it shorter.
I know I can specify the ErrorMessage for each property, but I rather not duplicate this all over the place:
[StringLength(25, ErrorMessage = "Max length is {1}")]
[DisplayName("Address")]
public virtual string BillAddress1 { get; set; }
Based on this post, Modify default ErrorMessage for StringLength validation, I subclassed StringLengthAttribute:
public class CustomStringLengthAttribute : StringLengthAttribute
{
public CustomStringLengthAttribute()
: this(20)
{
}
public CustomStringLengthAttribute(int maximumLength)
: base(maximumLength)
{
base.ErrorMessage = "Max length is {1}";
}
}
And changed to use CustomStringLengthAttribute instead:
[CustomStringLength(25)]
[DisplayName("Address")]
public virtual string BillAddress1 { get; set; }
This compiles fine, and I set a breakpoint in the CustomStringLengthAttribute constructor to verify that it gets hit, but unobtrusive validation no longer works - invalid data gets posted back to the controller.
It works fine when I do not use my subclassed version.
Also, here is the javascript validation:
if (validation.validateForm($('#addressForm'))) {
....
}
validateForm:
function validateForm(form) {
prepareValidationScripts(form);
var validator = $.data(form[0], 'validator');
return validator.form();
}
function prepareValidationScripts(form) {
if (form.executed)
return;
form.removeData("validator");
$.validator.unobtrusive.parse(document);
form.executed = true;
}
What am I missing?
Thanks.