简体   繁体   English

在某些情况下禁用mvc3客户端验证

[英]Disable mvc3 client-side validations under certain conditions

I am building a search form which needs multiple fields. 我正在建立一个需要多个字段的搜索表单。 A radio button indicates which fields are required for input like so : 单选按钮指示输入哪些字段是必需的,如下所示:

[ ] Field 1
[.] Field 2
    Field 3
[ ] Field 4

In the above case, Field 2 and Field 3 are now required since the associated radio button is checked. 在上述情况下,由于选中了关联的单选按钮,因此现在需要Field 2Field 3 To accomplish this, I have implemented the RequiredIf validation attribute, and it works properly. 为此,我实现了RequiredIf验证属性,它可以正常工作。

My problem are the other validations. 我的问题是其他验证。 In this case, Field 1 also has a minimum length validation. 在这种情况下, Field 1也具有最小长度验证。 If Field 1 has any value that does not respect the minimum length validation, the form is now invalid and cannot be submitted. 如果Field 1具有不符合最小长度验证的任何值,则该表格现在无效,无法提交。

I need a way to disable validation on the fields that are not required. 我需要一种方法来禁用不需要的字段上的验证。 (And also be able to set them back as another radio button is checked). (也可以在选中另一个单选按钮时将其重新设置)。

The fields cannot be set to "disabled=disabled" which solves the issue because of client requirements. 字段不能设置为“ disabled = disabled”,这可以解决此问题,因为客户要求。

I have tried removing the data-val attributes or setting them to false on the said fields, then parsing my form again, failing miserably. 我曾尝试在上述字段中删除data-val属性或将其设置为false ,然后再次解析我的表单,但失败了。

Edit: Just making sure. 编辑:只需确保。 The problem is client-side validations . 问题是客户端验证

Remember that there are 2 validations happening: client and server side. 请记住,正在发生两种验证:客户端和服务器端。 Hence, removing the data-val attribute will not help. 因此,删除data-val属性将无济于事。

Now, in your models I reckon you are using [attributes] to add these validation rules. 现在,在您的模型中,我认为您正在使用[属性]添加这些验证规则。 I don't think this method will not let you do conditional validations. 我认为这种方法不会让您进行条件验证。

In this case FluentValidation can help you. 在这种情况下,FluentValidation可以为您提供帮助。 http://fluentvalidation.codeplex.com/ http://fluentvalidation.codeplex.com/

It is quite simple to do, and you should be able to do something like: 这非常简单,您应该可以执行以下操作:

RuleFor(model => model.Field).NotEmpty().When(model => model.FieldEnabled);

Setting the fields as "disabled" works as intended. 将字段设置为“禁用”将按预期工作。 The client has changed his mind about this requirement. 客户对此要求已改变主意。 Sometimes it is the best solution. 有时这是最好的解决方案。

This is still open for better solutions. 这仍然是更好的解决方案。

Edit : 编辑:

I had not thought about searching for doc on the validation plugin. 我没有考虑过在验证插件上搜索文档。 There seems to be some pretty interesting methods available to use like rules ( "remove", rules ) . 似乎有一些非常有趣的方法可供使用,例如规则(“ remove”,rules)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM