简体   繁体   English

禁用JavaScript所需的验证

[英]Disable required validation by JavaScript

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. 我尝试将input元素的data-val属性设置为false,但这不起作用。

Some an idea? 有点想法吗?

Thanks in advance Tobias 在此先感谢Tobias

UPDATE: 更新:

Here is the java script code. 这是java脚本代码。 The data-val property is set correctly to false. data-val属性设置为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. 还有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();
                        }
                    })
            });

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验证功能于asp.net-MVC -3-部分-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. 如果您不想使用新的验证属性来处理此问题,则除了将data-val属性更改为false之外,您还需要做更多的事情。 When jQuery validate first parses your form it stores values in the form's data. 当jQuery验证首先解析您的表单时,它会将值存储在表单的数据中。 So simply changing data-val isn't enough. 所以简单地改变data-val是不够的。 You will additionally have to remove the stored validation data and reparse the form. 您还必须删除存储的验证数据并重新分析表单。 Here's an example: 这是一个例子:

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

You can use following JQuery to remove all validation rules of your element 您可以使用以下JQuery删除元素的所有验证规则

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

Same way you can use class name like, 你也可以使用类名

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

If you want to remove specific rule , do like this 如果要删除特定规则 ,请执行此操作

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

The unobtrusive javascript plugin provided by MVC doesn't process the data properties on the fly. MVC提供的不显眼的javascript插件不会动态处理数据属性。 Instead, it parses the results on document ready and caches them. 相反,它会解析文档准备好的结果并对其进行缓存。

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)以查看它是否为您提供了预期结果。

There are many ways to disable unobtrusive validation in Javascript but most of them seems a bit hackish... 有许多方法可以在Javascript中禁用不显眼的验证,但大多数方法看起来有点像hackish ......

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

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-val attribute to false . 另一种更灵活但更复杂的方法:您可以通过将data-val属性设置为false来禁用不显眼的验证。 But there is a trick... 但有一个诀窍......

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... 否则,即使您更改了验证,以前的错误消息仍然可见...

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. 我想,如果你做$('#mycheckbox').data('val','false') ,验证将跳过带有该id的项目。

Probably there is a more appropriate way to do it, but if not, take this. 可能有一种更合适的方法,但如果没有,请采取这种方式。

cheers. 干杯。

The default DataAnnotationsModelValidatorProvider adds a Required attribute to all value types. 默认DataAnnotationsModelValidatorProvider将Required属性添加到所有值类型。 You can change this behavior by adding the code in this answer . 您可以通过添加此答案中的代码来更改此行为。

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! 干杯!

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

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