I have a dynamic form where I can remove/add elements based on some selections.
Whenever I add new elements as a result of a toggle, I add their validation, and this happens one-way only. Can I be guaranteed that
- on removal of the element,
$(form).valid()
will still work -- it has the old validation but it won't find the element in the DOM, so validation will not fire; - on re-add of the element, the duplicate validation is harmless because it just overwrites the exact same previous one?
In other words, is the toggle is completely harmless even with a One-Way Validation Add only? It works in my test, but I wanted to confirm.
Here, when you toggle Radio Button 3, a dynamic field is added/removed. If you keep toggling I imagine you're always replacing the same Required rule, rather than accumulating new ones. And if you hide it, the validation still exists but the element isn't in the DOM so the Form is valid (see console output below).
$('#form').validate({
// No error messages, just highlight
errorPlacement : function(error, element) {}
});
$('#form input').each(function(index, item) {
$(item).rules('add', { required : true } );
});
$('input[type=radio][name=radiogroup').change(function() {
if ( $(this).val() == '3') {
$('#form').append('<input type="text" id="textDynamic" name="textDynamic"/><br/>');
// One-Way Add Validation: always (re-)add validation for dynamic field
$('#textDynamic').rules('add', { required : true } );
// End One-Way Add Validation
} else {
$('#form #textDynamic').remove();
}
});
$('#validate').click(function() {
if ($('#form').valid())
console.log('Valid');
else
console.log('Not valid');
});
.error {
background-color: yellow;
}
<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.js"></script>
<form id="form">
Field 1: <input type="text" id="text1" name="text1"/><br/><br/>
<input type="radio" id="radio1" name="radiogroup" value="1"/>Radio 1<br/>
<input type="radio" id="radio2" name="radiogroup" value="2"/>Radio 2<br/>
<input type="radio" id="radio3" name="radiogroup" value="3"/>Radio 3 (this toggles a new field)<br/>
</form>
<button id="validate">Validate Form</button>