dynamically remove an element's required attribute in ASP MVC?

谁说胖子不能爱 提交于 2019-12-07 17:37:14

问题


Is there a way, in an ASP MVC project using unobtrusive validation, to dynamically remove the Required attribute from an element?

The element is decorated with a Required annotation in the view model. I thought I could remove this by removing the html attribute, "data-val-required," with JQuery but client validation still treats the element as required. Is it impossible to manipulate the element's validation by manipulating the unobtrusive validation attributes?

This is what I tried, but it didn't work. I wanted to remove the required attribute if a check box was unchecked.

$("#chkTempHire").click(function () {

    var checked = $(this).attr("checked");
    var attr = $("#txtTempHireEndDate").attr("data-val-required");
    var hasAttr = false;

    if (typeof attr !== typeof undefined && attr !== false)
        hasAttr = true;

    if (!checked && hasAttr)
        $("#txtTempHireEndDate").removeAttr("data-val-required");
});

Am I missing something, or is it just not possible?

Thank you!


回答1:


You can use the .rules() method built into jQuery, you don't need to manually remove attributes.

To remove:

$("#txtTempHireEndDate").rules("remove", "required")

To add:

$("#txtTempHireEndDate").rules("add", "required")



回答2:


you can use rules function in jquery.validate

$("..").rules("add",....)
$("..").rules("remove",...)

http://jqueryvalidation.org/rules




回答3:


You must revalidate the form.

Just call the validate function from form, like this:

$('#FormId').valid();

You can also validate the control you've removed the attribute:

$('#txtTempHireEndDate').valid();



回答4:


$("#dailyFlow").removeAttr('data-val-required');



来源:https://stackoverflow.com/questions/31466002/dynamically-remove-an-elements-required-attribute-in-asp-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!