I am dynamically generating a series of fields based on a previous selection. As I do not know how many fields will be generated I cannot hard-code the validation script to check them.
However, all the fields that are generated will have an ID in a common format. For example,
- A score field all start with id="score_uniqueValue"
- A stanine field all start with id="stanine_uniqueValue"
- A 'years' field all start with id="years_uniqueValue"
- A 'months' field all start with id="months_uniqueValue"
Is there a way to adapt my jQuery validation script to check all fields in the form with that prefix and run a standard rule for it? This is the script I use for checking one individual field.
class OpAuthSignIn {
/*
* Init Sign In Form Validation
*
*/
static initValidationScore() {
jQuery('.js-validation-scores').validate({
errorClass: 'invalid-feedback animated fadeInDown',
errorElement: 'div',
errorPlacement: (error, e) => {
jQuery(e).parents('.form-group > div').append(error);
},
highlight: e => {
jQuery(e).closest('.form-group').removeClass('is-invalid').addClass('is-invalid');
},
success: e => {
jQuery(e).closest('.form-group').removeClass('is-invalid');
jQuery(e).remove();
},
rules: {
'score': {
required: true,
maxlength: 3,
number: true
},
'stanine': {
required: false,
maxlength: 1,
number: true
},
'years': {
required: false,
maxlength: 2,
number: true
},
'months': {
required: false,
maxlength: 2,
number: true
}
},
messages: {
'score' : 'Enter a valid 3 digit standardised score.',
'stanine' : 'Enter a valid stanine between 1 and 9.',
'years' : 'The ability age year value needs to be valid.',
'months' : 'Enter a valid month between 1 and 11.'
}
});
}
/*
* Init functionality
*
*/
static init() {
this.initValidationScore();
}
}// Initialize when page loads
jQuery(() => { OpAuthSignIn.init(); });