Parsley2: Conditional validation
Validates that at least one of four fields must be validated. If one is, it's assumed the group of fields is valid and the form can be submitted
by milz
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.0.7/parsley.min.js"></script>
<div class="invalid-form-error-message"></div>
<form id="demo-form">
<input type="text" name="field1" required data-parsley-errors-messages-disabled />
<input type="text" name="field2" required data-parsley-errors-messages-disabled />
<input type="text" name="field3" required data-parsley-errors-messages-disabled />
<input type="text" name="field4" required data-parsley-errors-messages-disabled />
<input type="submit" />
</form>
CSS
.invalid-form-error-message {
margin-top: 10px;
padding: 5px;
}
.invalid-form-error-message.filled {
border-left: 2px solid red;
}
JavaScript
$(document).ready(function() {
$('#demo-form').parsley().subscribe('parsley:form:validate', function (formInstance) {
// If any of these fields are valid
if ($("input[name=field1]").parsley().isValid() ||
$("input[name=field2]").parsley().isValid() ||
$("input[name=field3]").parsley().isValid() ||
$("input[name=field4]").parsley().isValid())
{
// Remove the error message
$('.invalid-form-error-message').html('');
// Remove the required validation from all of them, so the form gets submitted
// We already validated each field, so one is filled.
// Also, destroy parsley's object
$("input[name=field1]").removeAttr('required').parsley().destroy();
$("input[name=field2]").removeAttr('required').parsley().destroy();
$("input[name=field3]").removeAttr('required').parsley().destroy();
$("input[name=field4]").removeAttr('required').parsley().destroy();
return;
}
// If none is valid, add the validation to them all
$("input[name=field1]").attr('required', 'required').parsley();
$("input[name=field2]").attr('required', 'required').parsley();
$("input[name=field3]").attr('required', 'required').parsley();
$("input[name=field4]").attr('required', 'required').parsley();
// stop form submission
formInstance.submitEvent.preventDefault();
// and display a gentle message
$('.invalid-form-error-message')
.html("You must correctly fill the fields of at least one of these two blocks!")
.addClass("filled");
return;
});
});