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

4

9

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!

Inherit answered 16/7, 2015 at 23:4 Comment(3)
One solution is to use MVC's Foolproof Validation, which allows you to use attributes such as RequiredIf.Tildatilde
Conditional validation is what you're looking for, for example: #17971084Abbottson
Thanks, I am using FluentValidation and it works for me. I've just been trying to learn more about how the unobtrusive validation works.Inherit
A
29

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")
Apostrophize answered 17/7, 2015 at 9:56 Comment(2)
Success!! Thanks so much.Inherit
Very standard, neat & clean approach.Khasi
J
2

you can use rules function in jquery.validate

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

http://jqueryvalidation.org/rules

Julissa answered 17/7, 2015 at 9:9 Comment(0)
A
0

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();
Angelicangelica answered 17/7, 2015 at 2:4 Comment(0)
G
0

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

Glim answered 20/7, 2019 at 4:40 Comment(1)
Thanks for your contribution! Please add an explanation, especially the difference and benefits in comparison to the other answers.Devilish

© 2022 - 2024 — McMap. All rights reserved.