首页 > 解决方案 > 如何获得 jQuery 验证以检查具有公共前缀的所有字段?

问题描述

我正在根据先前的选择动态生成一系列字段。由于我不知道会生成多少个字段,我无法对验证脚本进行硬编码来检查它们。

但是,生成的所有字段都将具有通用格式的 ID。例如,

有没有办法调整我的 jQuery 验证脚本以检查表单中具有该前缀的所有字段并为其运行标准规则?这是我用于检查单个字段的脚本。

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(); });

标签: javascriptjqueryformsvalidation

解决方案


推荐阅读