Form validation - One of three fields must be completed

130 Views Asked by At

I use form validation (https://formvalidation.io/) to validate my forms.

In my form I have three phone number fields but I want at least one of the three to be filled in. How can I do this?

Looking forward to hearing from you

<div class="col-md-4">
  <div class="form-floating form-floating-outline">
    <input type="text" class="form-control telephone-fixe-mask" name="telephone_fixe" id="telephone_fixe" />
    <label for="telephone_fixe">Téléphone fixe</label>
  </div>
</div>

<div class="col-md-4">
  <div class="form-floating form-floating-outline">
    <input type="text" class="form-control telephone-mobile-mask" name="telephone_mobile" id="telephone_mobile" />
    <label for="telephone_mobile">Téléphone mobile</label>
  </div>
</div>

<div class="col-md-4">
  <div class="form-floating form-floating-outline">
    <input type="text" class="form-control telephone-mobile2-mask" name="telephone_mobile2" id="telephone_mobile2" />
    <label for="telephone_mobile2">Téléphone mobile 2</label>
  </div>
</div>
2

There are 2 best solutions below

0
cakepbm On

FormValidation.io might not have the function you want directly. Since you tagged jQuery, I assume you can use jQuery. The code you gave didn't include <form>, so I assume your form id is yourFormId

use this js code:

$('#yourFormId').on('submit', function(e) {
    var fixe = $('#telephone_fixe').val();
    var mobile = $('#telephone_mobile').val();
    var mobile2 = $('#telephone_mobile2').val();

    if (!fixe && !mobile && !mobile2) {
        alert('Please enter at least one phone number');
        e.preventDefault();
    }
});
1
Akaseb On

I just found on the FormValidation website. Requiring at least one field - formvalidation.io

Thank you cakepbm for your reply.