Search code examples
javascriptjqueryasp.net-mvcjquery-validateunobtrusive-validation

JQuery validate custom error message is not showing up


Following is the form validation javascript in my application:

$('#EmploymentHistoryForm').validate({
ignore: ':hidden, [readonly=readonly]',
rules: {
    'MemberJob.Phone': {
        PhoneFieldValidation: true
    }
},
messages: {
    'MemberJob.Phone': {
        PhoneFieldValidation: $.viewUrl.url.invaliedPhoneMessage
    }
},
showErrors: function (errorMap, errorList) {
    ShowErrors(errorMap, errorList, this.validElements());
},
submitHandler: function (form, event) {
    event.preventDefault();
    return false;
}
});

Here, $.viewUrl.url.invaliedPhoneMessage is set at the cshtml page (in ASP.NET MVC), and while debugging the javascript I can see proper value in that variable when $('...').validate function gets hit.

I have registered a new validator "PhoneFieldValidation" in JQuery validators collection:

$.validator.addMethod("PhoneFieldValidation", ValidatePhoneAndAltPhone);

Following is the rendered HTML for the input control for which I have added this validation rule:

<input class="PhoneFieldValidation" id="MemberJob_Phone" name="MemberJob.Phone" type="text" required="required" aria-required="true">

I can see the validation getting fired correctly. That means, "ValidatePhoneAndAltPhone" method is getting called, and returning a boolean result based on the input.

However, the error message is not getting displayed properly. It displays "Warning: No message defined for MemberJob.Phone" instead of "Invalid Phone Number".

While debugging through customMessage function of jquery.validate.js, I could see "this.settings.messages" collection is not having the message for "MemberJob.Phone" field, and that looks to be the root cause of this issue.

Any idea of how to resolve this issue?

I know we can add "data-msg-[rulename]" attribute in the HTML tag which will fix the issue. But I am sure the current approach I am following is also correct. Seems I am missing something.

Any help on this will be much appreciated.

Thanks


Solution

  • You never mentioned where $.viewUrl.url.invaliedPhoneMessage comes from.

    If there is already a message defined in your custom PhoneFieldValidation method, then you would not define a message within the messages object.

    Otherwise, you cannot use a JavaScript variable within the messages object without a function.

    The whole problem is being caused by the Unobtrusive plugin which is automatically constructing the .validate() method call. You cannot call .validate() more than once on the same form; and all subsequent calls are ignored. Instead, you can simply define the custom message for PhoneFieldValidation within its .addMethod() method.

    $.validator.addMethod("PhoneFieldValidation", function(value, element) {
        // your custom method function here;
    }, "This is your custom validation error message");