How to re-enable ASP.NET MVC unobtrusive validatio

2019-08-02 09:16发布

I have a form with unobtrusive validation set up and all works well under most circumstances. However there are cases where I have to disable a select element in the form and then sometimes the element gets re-enabled (Mostly when QA is trying every possible circumstance but still). When this happens the "required" validation rule on the select element no longer works.

I have tried removing and re-adding the required rule from the element's rules collection to no avail. I have tried wiring in and calling the validation extension described here which also does not work.

While I would love to know the root cause of the issue I am also open at this point to hacks and workarounds. I have a feeling this is a solved problem but I am not seeing it in my searches.

Thanks, Matthew

UPDATE: I am tempted to just select an answer and not fess up to my silly mistake, but that doesn't make the web better. What was going on is that the options in the select element are dynamic based on another field. The disabling happens when there are not items to go in the options based on that other field and when re-enabling the select the options are populated freshly. What I was doing was putting a "0" value in the default option when I recreated the options list which satisfied the "required" rule. I changed the default value to empty string and the issue went away.

What is the protocol for dealing with a question that isn't what it appeared to be? Should I close it?

2条回答
smile是对你的礼貌
2楼-- · 2019-08-02 10:04

In order to re-parse unobtrusive validation attributes, you must first clear validator and unobtrusiveValidation data created when the attributes were first parsed. Then, you can re-parse, like so:

$("form").removeData("validator");  
$("form").removeData("unobtrusiveValidation");  
$.validator.unobtrusive.parse("form");  
查看更多
Rolldiameter
3楼-- · 2019-08-02 10:15

What happens if you call

$.validator.unobtrusive.parse('#formId');

If I recall correctly, that should enable unobtrusive validation again on any elements that have unobtrusive data- attributes that are children of #formId.

查看更多
登录 后发表回答