MVC3 selectively validate client side

北城以北 提交于 2019-12-08 21:03:36

MVC 3 uses jQuery's validation plug-in by default and that plug-in will not validate disabled fields. Are the fields that you don't want to validate no longer needed if certain radio buttons are selected? If so, then you can just disable those elements and they won't be validated (and note that those disabled fields won't be posted to the server either).

e.g.

$('input').attr('disabled', 'disabled');

For complex validation it is best to hand code these. Data Annotations work great for 90% of your validation needs, but fail dismally with What/If scenarios.

For the client side use an event driven custom validation presented via jQuery Validation Plugin. For the server, use the CustomValidation attribute:

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.customvalidationattribute(v=vs.95).aspx

Using IClientValidatable is great if you have reusable custom validation, however it is wasted time for one off validations.

Alternatively use RemotValidation with a CustomValidation attribute that invalidates multiple fields.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!