通过 JavaScript 禁用所需的验证

发布于 2024-12-04 02:14:13 字数 933 浏览 0 评论 0 原文

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

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

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

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

有什么想法吗?

提前致谢 Tobias

更新:

这是 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();
                        }
                    })
            });

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

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.

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.

$(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();
                        }
                    })
            });

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

童话 2024-12-11 02:14:14

我已经使用自定义验证属性处理过类似的情况。您可以创建一个RequiredIf 属性,并仅当另一个属性为特定值时才将某些属性设为必需,而不是对属性使用Required 属性。

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

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

如果您不想使用新的验证属性来处理此问题,您将需要做更多的事情,而不仅仅是将 data-val 属性更改为 false。当 jQuery validate 第一次解析您的表单时,它会将值存储在表单的数据中。所以仅仅改变 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');

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.

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

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:

// 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');
挽心 2024-12-11 02:14:14

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

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

您可以使用类名称,例如,

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

如果您想删除特定规则 ,这样做

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

You can use following JQuery to remove all validation rules of your element

$('#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');
心凉怎暖 2024-12-11 02:14:14

MVC 提供的不显眼的 javascript 插件不会动态处理数据属性。相反,它会在文档就绪时解析结果并缓存它们。

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

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.

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

孤寂小茶 2024-12-11 02:14:14

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

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

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

干杯。

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

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

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

cheers.

初心 2024-12-11 02:14:14

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

  1. 最近发现你可以使用提交按钮来做到这一点。检查此链接以获取信息

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

当文档准备好时,不引人注目的验证数据会被缓存。这意味着,如果您在开头有 data-val='true' 并且稍后更改它,它仍然是 true

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

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'));
},

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

There are many ways to disable unobtrusive validation in Javascript but most of them seems a bit 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/

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

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

浅暮の光 2024-12-11 02:14:14

默认的DataAnnotationsModelValidatorProvider 向所有值类型添加一个Required 属性。您可以通过添加代码来更改此行为 这个答案

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

情话墙 2024-12-11 02:14:14

您可以实现一个自定义验证器,例如“RequiredIf”。

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

请参阅此答案:RequiredIf 条件验证属性

以及最终的博客文章:条件验证在 ASP.NET MVC 3

干杯!

You could implement a custom validator like "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).

See this answer : RequiredIf Conditional Validation Attribute

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

cheers!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文