I have a datetime field in my model which should be validated:
[DateValidation(ErrorMessage = "AccDate should be greater or equal to the current date")]
public DateTime? AccDate { get; set; }
DateValidation is a hand made class:
public class DateValidation : ValidationAttribute, IClientValidatable
{
public DateValidation()
{
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (validationContext.ObjectInstance is OrderModel)
{
var model = validationContext.ObjectInstance as OrderModel;
if (model.EndDate == null && model.AccDate.HasValue)
{
if (model.RecDate.HasValue && model.AccDate.Value < model.RecDate.Value)
{
var errorMessage = "AccDate should be greater than the RecDate";
return new ValidationResult(errorMessage);
}
if (model.AccDate.Value < DateTime.Now)
{
var errorMessage = "AccDate should be greater or equal to the current date";
return new ValidationResult(errorMessage);
}
}
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationType = "datevalidator";
yield return rule;
}
}
And also I have a datevalidator.js file:
$.validator.unobtrusive.adapters.add("datevalidator", [], function (values) {
values.rules['datevalidator'] = {
};
values.messages['datevalidator'] = values.message;
});
$.validator.addMethod("datevalidator", function (value, element, params) {
if (element.id == "AccDate") {
if (value) {
var nowDate = new Date($.now());
var accDate = new Date(value);
var recDate = new Date($("#RecDate").val());
if (accDate <= recDate) {
return false;
}
if (accDate < nowDate) {
return false;
}
return true;
}
}
});
By itself everything is working. Validation prevent me from doing unaceptable action BUT, I have an issue.
My error message which I receive is always equal to: "AccDate should be greater or equal to the current date"
As I understand, it happend because of [DateValidation(ErrorMessage = "AccDate should be greater or equal to the current date")]
and rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
. And so far I cant change it.
When the page is loaded, I am getting data-val-datevalidator
attribute for $("#AccDate")
which contains this error message. I tried to change it and make it different for each situation (similar to what ValidationResult
are returning):
if (accDate <= recDate) {
$("#AccDate").attr("data-val-datevalidator", "AccDate should be greater than the RecDate");
return false;
}
But there were no reaction at all (attribute value has changed but showed error message is still old one).
How can I change my error message for different one in datevalidator.js
?