先绑定input方法
<el-form-item label="字典名称" :label-width="formLabelWidth">
<el-input
@input="handleInputName"
v-model="formParent.name"
autocomplete="off"
placeholder="请输入中文、数字、字母或下划线"
/>
</el-form-item>
<el-form-item label="字典值" :label-width="formLabelWidth">
<el-input
@input="handleInputValue"
v-model="formParent.value"
autocomplete="off"
placeholder="请输入数字、字母或下划线"
/>
</el-form-item>
编写正则进行验证
const handleInputName = (value: any) => {
const regex = /^[\u4e00-\u9fa5A-Za-z0-9_]+$/;
if (!regex.test(value)) {
const lastValidIndex = value.search(regex);
if (lastValidIndex !== -1) {
formParent.name = value.substring(0, lastValidIndex);
} else {
// 如果没有找到任何合法字符,则清空输入框
formParent.name = "";
}
}
};
const handleInputValue = (value: any) => {
const regex = /^[A-Za-z0-9_]+$/;
if (!regex.test(value)) {
const lastValidIndex = value.search(regex);
if (lastValidIndex !== -1) {
formParent.value = value.substring(0, lastValidIndex);
} else {
formParent.value = "";
}
}
};