I've created a custom data annotation which works as expected on the client-side, correctly displaying a custom message to the user when the date entered is invalid. However, if the entry fails server-side validation, the default error message is returned. I'm unable to get to the root of why the custom message is not also displayed when failing server-side validation. Stepping through, everything seems fine in the debugger, but the output is ultimately incorrect. Any help would be much appreciated!
public class DobViewModel
{
[DateTypeWithPhrase()]
public DateTime? DateOfBirth { get; set; }
}
public class DataTypeWithPhraseAttributeAdapter : DataAnnotationsModelValidator<DateTypeWithPhraseAttribute>
{
private readonly DateTypeWithPhraseAttribute _attribute;
public DataTypeWithPhraseAttributeAdapter(ModelMetadata metadata, ControllerContext context, DateTypeWithPhraseAttribute attribute)
: base(metadata, context, attribute)
{
_attribute = attribute;
}
public static void SelfRegister()
{
DataAnnotationsModelValidatorProvider
.RegisterAdapter(
typeof(DateTypeWithPhraseAttribute),
typeof(DataTypeWithPhraseAttributeAdapter));
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
return new[] { new ModelClientValidationDateRule(_attribute.ErrorMessage) };
}
}
public class DateTypeWithPhraseAttribute : DataTypeAttribute
{
public DateTypeWithPhraseAttribute() : base(DataType.Date)
{
ErrorMessageResourceName = null;
ErrorMessage = ErrorPhrase;
}
public string ErrorPhrase = "Invalid Date";
}