MVC3 selectively validate client side

怎甘沉沦 提交于 2019-12-23 04:15:34

问题


Each form in the application has a set of radiobuttons. Once selected, only certain fields associated with that radiobutton will need to be validated.

I am using MVC 3 and need the validation to work client side.

  1. Simply using DataAnnotations I can only validate all fields on the form.

  2. IValidatableObject doesn't work clientside.

  3. IClientValidatable looks like it might do the job, but it seems I would have to write a new attribute for every standard DataAnnotation attribute.

  4. RemoteValidation works with one field at a time.

  5. Another option would be to drop MVC3 validation and do it all using jQuery. I don't have a problem with this as such but would like to use MVC3 and reduce coding/maintenance in preparation for a much larger project.

  6. Could I still use MVC3 validation but then use jQuery to add/remove validation fields from validation whenever a radiobutton is selected?

If anyone can help with some suggestions as to the best way to approach this, it would be much appreciated.


回答1:


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');




回答2:


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.



来源:https://stackoverflow.com/questions/5425829/mvc3-selectively-validate-client-side

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