基本结构

在这里插入图片描述
model 表单数据对象
rules 验证对象
prop model 的键名

<template>
	<el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
		<el-form-item label="手机号" prop="mobile">
			<el-input v-model="ruleForm.mobile" />
		</el-form-item>
		<el-form-item label="密码" prop="pass">
			<el-input v-model="ruleForm.pass" type="password" />
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
		</el-form-item>
	</el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";

const phoneRegular = /^1[23456789]\d{9}$/;

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
	mobile: "",
	pass: "",
});

function customMobile(_: any, value: any, callback: any) {
	if (phoneRegular.test(value)) callback();
	else callback(new Error("请输入正确的手机号"));
}
const rules = reactive<FormRules<typeof ruleForm>>({
	mobile: [
		{ required: true, message: "请输入手机号", trigger: ["blur", "change"] },
		// 正则
		{ pattern: phoneRegular, message: "请输入正确的手机号", trigger: ["blur", "change"] },
		// 自定义验证
		{ validator: customMobile, trigger: ["blur", "change"] },
	],
	pass: [{ required: true, message: "请输入密码", trigger: ["blur", "change"] }],
});

const submitForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid) => {
		if (valid) {
			console.log("submit!");
		} else {
			console.log("error submit!");
			return false;
		}
	});
};
</script>

正则验证

const phoneRegular = /^1[23456789]\d{9}$/;

const rules = reactive<FormRules<typeof ruleForm>>({
	mobile: [
		// 正则
		{ pattern: phoneRegular, message: "请输入正确的手机号", trigger: ["blur", "change"] },
	]
});

自定义函数验证

const phoneRegular = /^1[23456789]\d{9}$/;
function customMobile(_: any, value: any, callback: any) {
	if (phoneRegular.test(value)) callback();
	else callback(new Error("请输入正确的手机号"));
}
const rules = reactive<FormRules<typeof ruleForm>>({
	mobile: [
		// 自定义验证
		{ validator: customMobile, trigger: ["blur", "change"] },
	]
});

数据结构嵌套对象验证写法

在这里插入图片描述

<template>
	<el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
		<el-form-item label="手机号" prop="mobile">
			<el-input v-model="ruleForm.mobile" />
		</el-form-item>
		<el-form-item label="密码" prop="user.pass">
			<el-input v-model="ruleForm.user.pass" type="password" />
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
		</el-form-item>
	</el-form>
</template>

<script lang="ts" setup>
const ruleForm = reactive({
	mobile: "",

	user: {
		pass: "",
	},
});

const rules = reactive<FormRules<typeof ruleForm>>({
	mobile: [{ required: true, message: "请输入手机号", trigger: ["blur", "change"] }],
	"user.pass": [{ required: true, message: "请输入密码", trigger: ["blur", "change"] }],
});
</script>

数据结构为数组验证写法

<template>
	<el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
		<el-form-item label="图片" prop="images">
			<div>请选择图片</div>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
			<el-button type="primary" @click="ruleForm.images.push('http:')">追加 images {{ ruleForm.images }}</el-button>
		</el-form-item>
	</el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";

interface RuleForm {
	images: string[];
}
const ruleFormRef = ref<FormInstance>();
const ruleForm: RuleForm = reactive({
	images: [],
});

const rules = reactive<FormRules<typeof ruleForm>>({
	images: [
		{ required: true, message: "请上传图片", trigger: ["blur", "change"] },
		// 定义类型必填 array ,数组 length 必须为 2
		{ type: "array", len: 2, message: "请上传两张图片", trigger: ["blur", "change"] },
		// 验证数组范围 2-4
		{ type: "array", min: 2, max: 4, message: "请上传2-4张图片", trigger: ["blur", "change"] },
	],
});

const submitForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid) => {
		if (valid) {
			console.log("submit!");
		} else {
			console.log("error submit!");
			return false;
		}
	});
};
</script>

validateField 验证具体的某个某些字段

import type { FormInstance } from 'element-plus';
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
	mobile: "",
	pass: "",
});

ruleFormRef?.value?.validateField(['mobile'], flag => {
	// flag true 全部验证通过, false 验证不通过
})

// 验证多个写法
ruleFormRef?.value?.validateField(['mobile','pass'], flag => {})

动态切换是否需要添加验证规则

动态修改 rules,而不是修改 prop
在这里插入图片描述

<template>
	<el-form ref="ruleFormRef" :model="ruleForm">
		<el-form-item label="手机号" prop="mobile" :rules="flag ? rules['mobile'] : ruleEmpty">
			<el-input v-model="ruleForm.mobile" />
		</el-form-item>
		<el-form-item label="密码" prop="pass" :rules="flag ? rules['pass'] : ruleEmpty">
			<el-input v-model="ruleForm.pass" type="password" />
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>

			<el-button type="primary" @click="flag = !flag">切换 flag {{ flag }}</el-button>
		</el-form-item>
	</el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
	mobile: "",
	pass: "",
});

const flag = ref(true);
const ruleEmpty = { required: false };
const rules = reactive<FormRules<typeof ruleForm>>({
	mobile: [{ required: true, message: "请输入手机号", trigger: ["blur", "change"] }],
	pass: [{ required: true, message: "请输入密码", trigger: ["blur", "change"] }],
});

const submitForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid) => {
		if (valid) {
			console.log("submit!");
		} else {
			console.log("error submit!");
			return false;
		}
	});
};
</script>

判断一个数组是否有一个有值和是否全部有值

以值为字符串数组为例,其他增加判断

const broker = reactive({
  project: [
    {
      name: '',  
      date: [], 
    },
  ],
});

flag.value = broker.education.some(item => Object.values(item).some(value => value.length > 0));
flag2.value = broker.education.every(item => Object.values(item).every(value => value.length > 0));
<el-form ref="ruleFormRef" :hide-required-asterisk="true" :model="broker" :rules="rules">
  <div v-for="(item, index) in broker.education" :key="index">
    <el-form-item :prop="`education.${index}.name`" :rules="rules['education.name']">
      <el-input v-model="item.name" placeholder="请填写学校名称" />
    </el-form-item>
  </div>
</el-form>

const rules = reactive({
  'education.name': [
    { required: true, message: '请填写学校名称', trigger: ['blur', 'change'] }
  ],
})

const broker: formType = reactive({
  education: [
    {  name: '' },
    // ...
  ]
})

在这里插入图片描述

Logo

前往低代码交流专区

更多推荐