Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
36
rated 0 times [  41] [ 5]  / answers: 1 / hits: 21259  / 9 Years ago, thu, july 16, 2015, 12:00:00

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!


More From » jquery

 Answers
16

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)

[#65776] Wednesday, July 15, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
isaacvalentinn

Total Points: 325
Total Questions: 120
Total Answers: 131

Location: North Korea
Member since Tue, Jun 16, 2020
4 Years ago
isaacvalentinn questions
Mon, Jan 18, 21, 00:00, 3 Years ago
Mon, Nov 23, 20, 00:00, 4 Years ago
Wed, Sep 23, 20, 00:00, 4 Years ago
;