禁用 JavaScript 所需的验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7389652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:05:39  来源:igfitidea点击:

Disable required validation by JavaScript

javascriptasp.net-mvc-3validationunobtrusive-javascript

提问by Tobias

I have a create form to create an object. The create model has some properties that are only visible (.hide, .show()) if a checkbox is checked and that are marked required (by Attribute in Model).

我有一个创建表单来创建一个对象。如果选中复选框并标记为必需(通过模型中的属性),则创建模型具有一些仅可见的属性(.hide、.show())。

Unfortunatly when the checkbox is not checked, the required validation is performed on the properties hidden.

不幸的是,当未选中该复选框时,将对隐藏的属性执行所需的验证。

How can I disable the required validation for this properties?

如何禁用此属性所需的验证?

I tried setting the data-val property of the input element to false but this does not work.

我尝试将输入元素的 data-val 属性设置为 false 但这不起作用。

Some an idea?

有什么想法?

Thanks in advance Tobias

预先感谢托比亚斯

UPDATE:

更新:

Here is the java script code. The data-val property is set correctly to false. it seems that validation does not care of this property. there is also the data-val-required attribute but there is a text i could not backup.

这是java脚本代码。data-val 属性正确设置为 false。似乎验证并不关心这个属性。还有 data-val-required 属性,但有一个我无法备份的文本。

$(function () {
                $("#MyCheckbox")
                    .change(function () {
                        if (this.checked) {
                            $("#divWithChildProperties [data-val]").attr("data-val", true);
                            $("#divWithChildProperties ").show();
                        }
                        else {
                            $("#divWithChildProperties [data-val]").attr("data-val", false);
                            $("#divWithChildProperties ").hide();
                        }
                    })
            });

回答by bbak

I've handled cases like this with a custom Validation Attribute. Instead of using the Required attribute for properties you could make a RequiredIf attribute and make some of your properties required only if another property is a certain value.

我已经使用自定义验证属性处理过这样的情况。除了对属性使用 Required 属性之外,您还可以创建一个 RequiredIf 属性,并且仅当另一个属性是特定值时才需要某些属性。

Here is a post about creating an attribute like this (the example in the middle of the page under the 'A more complex custom validator' section): http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2

这是一篇关于创建这样的属性的帖子(“更复杂的自定义验证器”部分下页面中间的示例):http: //www.devtrends.co.uk/blog/the-complete-guide -to-validation-in-asp.net-mvc-3-part-2

If your checkbox represents a property in your model this should work fine.

如果您的复选框代表模型中的一个属性,这应该可以正常工作。

If you don't want to handle this with a new validation attribute you will have to do a few more things than just change the data-val attribute to false. When jQuery validate first parses your form it stores values in the form's data. So simply changing data-val isn't enough. You will additionally have to remove the stored validation data and reparse the form. Here's an example:

如果您不想使用新的验证属性来处理这个问题,您将不得不做更多的事情,而不仅仅是将 data-val 属性更改为 false。当 jQuery 验证首先解析您的表单时,它会将值存储在表单的数据中。所以仅仅改变 data-val 是不够的。您还必须删除存储的验证数据并重新解析表单。下面是一个例子:

// Do this after you've removed/modified the data-val attribute
$('selector for your form').removeData('unobtrusiveValidation');
$('selector for your form').removeData('validator');
$.validator.unobtrusive.parse('selector for your form');

回答by Karthikeyan P

You can use following JQueryto remove all validation rules of your element

您可以使用以下JQuery删除元素的所有验证规则

$('#ElementId').rules('remove');

Same way you can use class namelike,

同样,您可以使用类名,例如,

$('.ElementClassName').rules('remove');

If you want to remove specific rule, do like this

如果要删除特定规则,请执行以下操作

$('#ElementId').rules('remove', 'required');

回答by DMac the Destroyer

The unobtrusive javascript plugin provided by MVC doesn't process the data properties on the fly. Instead, it parses the results on document ready and caches them.

MVC 提供的不显眼的 javascript 插件不会即时处理数据属性。相反,它解析文档准备好的结果并缓存它们。

Try calling $.validator.unobtrusive.parse(myForm)on your form after modifying the property in question to see if it gives you expected results.

$.validator.unobtrusive.parse(myForm)在修改相关属性后尝试调用您的表单,看看它是否给您预期的结果。

回答by vtortola

Unobstrusive validation looks for this attribute data-val="true"

不显眼的验证会查找此属性 data-val="true"

I guess, that if you do a $('#mycheckbox').data('val','false'), the validation will skip a item with that id.

我猜,如果您执行 a $('#mycheckbox').data('val','false'),验证将跳过具有该 ID 的项目。

Probably there is a more appropriate way to do it, but if not, take this.

可能有更合适的方法来做到这一点,但如果没有,请采取这个。

cheers.

干杯。

回答by Gudradain

There are many ways to disable unobtrusive validation in Javascript but most of them seems a bit hackish...

有很多方法可以在 Javascript 中禁用不显眼的验证,但大多数方法似乎有点黑客......

  1. Recently found that you can do it with submit button. Check this link for info
  1. 最近发现你可以用提交按钮来做到这一点。检查此链接以获取信息

http://www.nitrix-reloaded.com/2013/09/16/disable-client-side-validation-on-a-button-click-asp-net-mvc/

http://www.nitrix-reloaded.com/2013/09/16/disable-client-side-validation-on-a-button-click-asp-net-mvc/

//this
<script type="text/javascript">
  document.getElementById("backButton").disableValidation = true;
</script>
//or this
<input type="submit" name="backButton" value="Back" 
 title="Go back to Prev Step" disableValidation="true" />
//or this
<input type="submit" name="backButton" value="Back"
 title="Go back to Prev Step" class="mybtn-style cancel" />
  1. Another way that is more flexible but more complicated : you can disable unobtrusive validation by setting the data-valattribute to false. But there is a trick...
  1. 另一种更灵活但更复杂的方法是:您可以通过将data-val属性设置为false. 但是有一个技巧...

Unobtrusive validation data is cached when the document is ready. This means that if you have data-val='true'at the beginning and that you change it later on, it will still be true.

当文档准备好时,不显眼的验证数据会被缓存。这意味着,如果您data-val='true'在开始时使用并且稍后更改它,它仍然是true.

So, if you want to change it after the document is ready, you also need to reset the validator which will erase the cached data. Here is how to do it :

因此,如果您想在文档准备好后更改它,您还需要重置验证器,这将删除缓存的数据。这是如何做到的:

disableValidation: function () {
    //Set the attribute to false
    $("[data-val='true']").attr('data-val', 'false');

    //Reset validation message
    $('.field-validation-error')
    .removeClass('field-validation-error')
    .addClass('field-validation-valid');

    //Reset input, select and textarea style
    $('.input-validation-error')
    .removeClass('input-validation-error')
    .addClass('valid');

    //Reset validation summary
    $(".validation-summary-errors")
    .removeClass("validation-summary-errors")
    .addClass("validation-summary-valid");

    //To reenable lazy validation (no validation until you submit the form)
    $('form').removeData('unobtrusiveValidation');
    $('form').removeData('validator');
    $.validator.unobtrusive.parse($('form'));
},

You don't need to reset all the messages, input styles and validation summary to be able to submit the form but it's useful if you want to change the validation after the page is loaded. Otherwise, even if you change the validation, the previous error messages will still be visible...

您无需重置所有消息、输入样式和验证摘要即可提交表单,但如果您想在页面加载后更改验证,这会很有用。否则,即使您更改了验证,之前的错误消息仍将可见...

回答by counsellorben

The default DataAnnotationsModelValidatorProvideradds a Required attribute to all value types. You can change this behavior by adding the code in this answer.

默认情况下DataAnnotationsModelValidatorProvider,所有值类型都添加了一个必需的属性。您可以通过在此答案中添加代码来更改此行为。

回答by fredlegrain

You could implement a custom validator like "RequiredIf".

您可以实现像“RequiredIf”这样的自定义验证器。

That will keep your model design quite obvious (unlike client-side-only solutions proposed). This allows you to keep the validation logic separate from display logic (that's what MVC is all about).

这将使您的模型设计非常明显(与提出的仅客户端解决方案不同)。这允许您将验证逻辑与显示逻辑分开(这就是 MVC 的全部内容)。

See this answer : RequiredIf Conditional Validation Attribute

请参阅此答案:RequiredIf Conditional Validation Attribute

and ultimately that blog post : Conditional Validation in ASP.NET MVC 3

最后是那篇博文:ASP.NET MVC 3 中的条件验证

cheers!

干杯!