Disable required data Annotation via jquery

Asked

Viewed 86 times

0

I need to disable the required of dataannotation via jquery, and need to disable also the data-required, this I have managed, but not required, I am trying to do this way:

$("#Contato").attr("required", "false");
$("#Contato").attr("data-required", "false");

I’ve tried it like this:

 $("#Contato").attr("data-val-required", "false");

But no way works. How can I take advantage of dataannotation and depending on the condition disable ?

  • Have you tried $("#Contato").removeAttr("required");?

  • @Sam already yes, and the same problem occurs.

  • If I’m not mistaken false is no quotes?!

  • @Leandrade even so did not give, it was my first attempt.

  • As you put it in the question, it seems that you are wanting to remove the attribute of the element, which would work perfectly what I put in the previous comment. Now, if you want to manipulate a component or plugin, that’s something else. You would have to show code of how you are using the component.

  • @Sam I said I would have a condition, sorry if it wasn’t so clear, until then I managed to do it this way if (Tipo == 'Outros') {
 $('#TipoPessoa').rules('remove', 'required');
 $("#TipoPessoa").attr("data-required", "false");} else {
 $('#TipoPessoa').rules('add', 'required');
 $("#TipoPessoa").attr("data-required", "true");} I don’t know if it’s the best way, but it worked.

Show 1 more comment

1 answer

0


$(document).ready(function() {

$('#firstname').prop('required', false);
$('#firstname').removeAttr('data-required');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  First name:<br>
  <input type="text"  required  data-required name="firstname"  id="firstname" ><br>
  Last name:<br>
  <input type="text" required  data-required name="lastname" id="lastname">
</form>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.