Reputation: 313
I have a from with 2 input fields: Cellphone and Telephone. I want that at least one of those fields are required so the form can be submited. Either you enter the cellphone number and telephone input is no longer required or the other way around.
<input class="form-control telephone" type="text" placeholder="Telephone" required="required" maxlength="100" pattern="^\+?[0-9 /-]*$"/>
<input class="form-control cellphone" type="text" placeholder="Cellphone" required="required" maxlength="100" pattern="^\+?[0-9 /-]*$"/>
I found that the Jquery validator has conditional statements but i dont know how to use them or they didnt work in my code. Heres what i had
$("#myForm").validate({
firstInput: {
required: function(element){
return $(".cellphone").val().length > 0;
}
},
secondInput: {
required: function(element){
return $(".telephone").val().length > 0;
}
}
});
Upvotes: 0
Views: 338
Reputation: 1258
1) You need to put the validation rules in the rules object.
2) Your if statements are wrong. Input is required (required: true
) if the other input is empty (otherInput.val().length == 0
).
3) You need to specify name attributes to your inputs.
$("#myForm").validate({
rules: {
firstInput: {
required: function(element){
return $(".cellphone").val().length == 0;
}
},
secondInput: {
required: function(element){
return $(".telephone").val().length == 0;
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<form id='myForm'>
<input class="form-control telephone" type="text" placeholder="Telephone" maxlength="100" name="firstInput" pattern="^\+?[0-9 /-]*$"/>
<input class="form-control cellphone" type="text" placeholder="Cellphone" name="secondInput" maxlength="100" pattern="^\+?[0-9 /-]*$"/>
<input type="submit">
</form>
Upvotes: 2