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!
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!
Share Improve this question edited Jul 17, 2015 at 3:28 Daniel Hoffmann-Mitscherling 2,3791 gold badge17 silver badges23 bronze badges asked Jul 16, 2015 at 23:04 MikeMike 4092 gold badges11 silver badges20 bronze badges 3 |4 Answers
Reset to default 30You 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")
you can use rules function in jquery.validate
$("..").rules("add",....)
$("..").rules("remove",...)
http://jqueryvalidation.org/rules
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();
$("#dailyFlow").removeAttr('data-val-required');
RequiredIf
. – Icemanind Commented Jul 16, 2015 at 23:12