1、校验器方法 - forbiddenCharValidator
const idUpdateFormRef = ref(null);
const forbiddenCharValidator = (rule, value, callback) => {
const forbiddenCharacters = [
'as',
'for',
'default',
'in',
'join',
'left',
'inner',
'right',
'where',
'when',
'case',
'select'
];
for (let forbiddenCharacter of forbiddenCharacters) {
if (value && value === forbiddenCharacter) {
callback(new Error(`不能使用关键字 '${forbiddenCharacter}' 作为ID`));
return;
}
}
callback();
};
2、校验规则
const idFormRules = {
guidText: [
{
required: true,
message: '请输入ID',
trigger: 'blur'
},
{ validator: forbiddenCharValidator, trigger: 'blur' },
{ min: 8, max: 8, message: 'ID必须为8位', trigger: 'blur' },
{
pattern: /^[a-z0-9]+$/,
message: '输入只能包含小写字母和数字',
trigger: 'blur'
}
]
};
3、 确定事件
通过校验才能关闭弹窗
const confirmModifyIdDialog = () => {
guidUpdateFormRef.value.validate((valid) => {
if (valid) {
openModifyIdDialog.value = false;
}
});
};
4、html
<el-dialog v-model="openModifyIdDialog" title="修改ID">
<el-form
ref="idUpdateFormRef"
:model="idUpdateForm"
:rules="idFormRules"
>
<el-form-item
label="ID:"
style="margin-left: 20px"
prop="idText"
>
<el-input
v-model="idUpdateForm.idText"
placeholder="请输入ID"
/>
</el-form-item>
</el-form>
<template #footer>
<div class="dialog-footer">
<el-button @click="cancelModifyIdDialog">取消</el-button>
<el-button type="primary" @click="confirmModifyIdDialog">
确定
</el-button>
</div>
</template>
</el-dialog>
以上就是实现关键字校验器的具体步骤。