MVC3有选择地验证客户端 [英] MVC3 selectively validate client side

查看:63
本文介绍了MVC3有选择地验证客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应用程序中的每个表单都有一组单选按钮.选择后,仅需要验证与该单选按钮关联的某些字段.

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

我正在使用MVC 3,并且需要进行验证才能在客户端工作.

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

  1. 仅使用DataAnnotations,我只能验证表单上的所有字段.

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

IValidatableObject在客户端不起作用.

IValidatableObject doesn't work clientside.

IClientValidatable似乎可以完成工作,但似乎我必须为每个标准DataAnnotation属性编写一个新属性.

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

RemoteValidation一次只能处理一个字段.

RemoteValidation works with one field at a time.

另一个选择是删除MVC3验证,并使用jQuery完成所有操作.我对此没有任何问题,但是我想使用MVC3并减少编码/维护,以便为更大的项目做准备.

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.

我是否仍可以使用MVC3验证,但是一旦选择单选按钮,然后使用jQuery从验证中添加/删除验证字段?

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默认使用jQuery的验证插件,并且该插件不会验证禁用的字段.如果选中了某些单选按钮,是否不再需要您不想验证的字段?如果是这样,那么您只需禁用这些元素,它们就不会被验证(请注意,那些禁用的字段也不会发布到服务器上).

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).

例如

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

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

这篇关于MVC3有选择地验证客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆