0

How do i override the default error message in unobtrusive validation?.

i tried to use $.validator.unobtrusive.messages.dobvalidation to the reset the error message for that validation type but without any success.

    //DOB Validation
    jQuery.validator.unobtrusive.adapters.add("dobvalidation", function (options) {
            options.rules["dobvalidation"] = "true";
            options.messages["dobvalidation"] = options.message;
    });

    jQuery.validator.addMethod("dobvalidation",
        function (value, element, param) {
            if (value.length > 3) {
                var test = $(element).attr('data-val-dobvalidation-err1');
                $.validator.unobtrusive.messages.dobvalidation = test; // this line of code is 
                                                                          not working
                return false;
            }
            return true;
        });



public class DateOfBirthFluentValidationPropertyValidator : FluentValidationPropertyValidator
{
    public int? MinimumAge { get; set; }
    public string DateFormat { get; set; }
    public string InvalidDateFormatErrorMessage { get; set; }
    public string YoungerThanMinimumErrorMessage { get; set; }

    public DateOfBirthFluentValidationPropertyValidator(ModelMetadata metadata, ControllerContext controllerContext, PropertyRule rule, IPropertyValidator validator,
         int? minimumAge = null,  string dateFormat = null,string invalidDateFormatErrorMessage = null, string youngerThanMinimumAgeErrorMessage = null)
        : base(metadata, controllerContext, rule, validator)
    {
        MinimumAge = minimumAge;
        DateFormat = dateFormat;
        InvalidDateFormatErrorMessage = invalidDateFormatErrorMessage;
        YoungerThanMinimumErrorMessage = youngerThanMinimumAgeErrorMessage;
    }


    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        var rule = new ModelClientValidationRule
        {
            ValidationType = "dobvalidation",
            ErrorMessage = InvalidDateFormatErrorMessage
       };

        rule.ValidationParameters.Add("err1", InvalidDateFormatErrorMessage);

        yield return rule;
    }

}
user845405
  • 1,461
  • 5
  • 23
  • 43

1 Answers1

0

While its the tedious and often the unusual thing to do, since all of it is controlled through the JS file and it overrides the options that are set explicitly. You can refer to these links which might provide you more insight on this.

Override Unobtrusive JS Validation - 1

Override Unobtrusive JS Validation - 2

Community
  • 1
  • 1
Dhrumil
  • 3,221
  • 6
  • 21
  • 34