ElementPlus中form的表单验证不生效

需要按照官网的书写规范,并且表单绑定的数据对象要是最外层的,
el-form-item元素要有prop属性
之前绑定的是

state.ruleForm,这样是不生效的,

const state = reactive({
	isShowPassword: false,
	ruleForm: {
		userName: '',
		password: '',
	},
	loading: {
		signIn: false,
	},
});

需要改成这样

interface RuleForm {
	userName: string;
	password: string;
}

const ruleForm = reactive<RuleForm>({
	userName: '',
	password: '',
});

验证rules数组写法

import { FormRules } from 'element-plus';

const rules = reactive<FormRules<RuleForm>>({
	userName: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
	password: [
		{
			required: true,
			message: '密码不能为空',
			trigger: 'change',
		},
	],
});

使用,给form定义ref,其中有属性的绑定

:rules="rules" ref="ruleFormRef" :model="ruleForm"
import { FormInstance, FormRules } from 'element-plus';
const ruleFormRef = ref<FormInstance>();

登录按钮中将 ruleFormRef 当做参数传入

@click="onSignIn(ruleFormRef)"

onSignIn方法中进行验证

const onSignIn = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
    //添加 async 以便返回 Promise
	formEl.validate(async (valid) => {
		if (valid) {
			//验证通过,发起后端请求
			
		} else {
			//验证不通过
		}
	});
};
posted @ 2024-05-22 11:47  猝死的路上  阅读(656)  评论(0编辑  收藏  举报