0

I've created a MVC 5 form that dynamically adds fields using the editorfor function. The fields are automatically assigned new ids and names by MVC so that the property I've defined in my model is not the same id and name. This is causing MVC validation to fail to retrieve the error message I've specified in my properties data annotations. To rectify this I am attempting to assign a specific error message to the element. However, I cannot apply validator.showErrors to the element because when I attempt to validate the specific element the result is undefined. Why is var validator in the following code return undefined?

Thanks...

$('form').removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse($('form'));

var validator = $('#myClass_0__Age').validate();

2 Answers 2

2

Actually I had the correct jQuery function all along:

$('form').removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse($('form'));

However my page was displaying the default MVC validation errors for my nested class properties, instead of those I've specified in the data annotations of those properties, because I was re-parsing the unobtrusive validators (jQuery function above) in my submit function and not in the Json function I used to input the additional properties. Moving the line above to the Json response of my property/element load function fixed the issue.

Sign up to request clarification or add additional context in comments.

Comments

0

I believe jquery validate initializes based on classes on your elements when the form initially loads.

Because you are dynamically adding elements that need validate you will have to register them for validation yourself when you load them.

$('#elementID').rules('add', 'required');

Try calling that after you add an element to your form on the element, then see if the validator stops returning undefined.

E.g. even though you are adding them, if they don't have all the right classes it won't add them to validation. I am pretty sure that using the above code will do all those classes for you and wire it up in the validation engine.

1 Comment

Thank you for your response. You helped to get me on the right track as you were correct that the jQuery validation needed to be updated when my page elements were loaded. Luckily, I didn't need to register each element as you described, simply re-parsing the form (see response below) was enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.