3
votes

I have a form where I need to do conditional validation for 3 field. These fields are Email, FirstName and LastName. So Email field text-box has value, I need not have to validate FirstName & LastName, I mean later 2 can be empty . If FirstName & LastName field have value, Email can be empty.

I am using HTML5 required attribute.

How to enable disable HTML5 required validator using jQuery ?

4

4 Answers

3
votes

To remove

$("#txt").removeAttr("required");

To add

$("#txt").attr("required","");
0
votes

Try this:

jQuery

 $('#Email').removeAttr('required');​​​​​
0
votes

This might help you

$('button').click(function(){
  $('input').each(function(){
    $(this).prop('required', !$(this).attr('required'))
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" nam="FirstName" placeholder="First Name" required/>
<input type="text" nam="LastName" placeholder="Last Name" required/>
<input type="text" nam="Email" placeholder="Email" required/>

<br/>
<button>
Enable/Disable All inputs
</button>

It's like toggling the required attribute.

0
votes

Check for value and remove required attribute.

$('#btnSubmit').on('click', function() {
  if ($('input[name=last]').val() != "" && $('input[name=first]').val() != "")
    $('input[name=Email]').removeAttr("required");
  else if ($('input[name=Email]').val() != "") $('input[name=first],input[name=last]').removeAttr("required");

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
  First:
  <input type="text" name="first" value="" required />
  <br />Last:
  <input type="text" name="last" value="" required />
  <br />Email:
  <input type="text" name="Email" value="" required />
  <br />
  <input type="submit" value="Submit" id="btnSubmit" />
</form>