Validating multiple inputs as one

In some cases, you need to validate a value which is combined by various fields. For instance, a Birthday field might be a combination of Date, Month and Year one.
This example show a way to deal with these cases. The following form requires all of Date, Month and Year fields. Also, the combination of them must be a valid date.
First, we need to create a hidden field that its value is generated from Date, Month and Year fields:
<form id="demoForm" method="POST">
<input type="text" name="date" placeholder="Date" />
<input type="text" name="month" placeholder="Month" />
<input type="text" name="year" placeholder="Year" />
<!-- Create a hidden field which is combined by 3 fields above -->
<input type="hidden" name="dob" />
</form>
We set the validator rules for that hidden field as usual:
const form = document.getElementById('demoForm');
const fv = FormValidation.formValidation(
form,
{
fields: {
dob: {
validators: {
notEmpty: {
message: 'Please fill out each field'
},
date: {
format: 'YYYY/MM/DD',
message: 'Please enter a valid date',
},
}
}
},
plugins: {
...
},
}
);
Finally, when any of Date, Month and Year fields changes its value, we need to update the hidden field value and revalidate it using the revalidateField() method:
const keyupHandler = function () {
const y = form.querySelector('[name="year"]').value;
const m = form.querySelector('[name="month"]').value;
const d = form.querySelector('[name="date"]').value;
// Set the dob field value
const dob = y === '' || m === '' || d === '' ? '' : [y, m, d].join('/');
form.querySelector('[name="dob"]').value = dob;
// Revalidate it
fv.revalidateField('dob');
};
form.querySelector('[name="year"]').addEventListener('keyup', keyupHandler);
form.querySelector('[name="month"]').addEventListener('keyup', keyupHandler);
form.querySelector('[name="date"]').addEventListener('keyup', keyupHandler);
Here is the working example:
Validating multiple inputs as one

See also