开发者

MVC3 selectively validate client side

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜