element-ui 表单校验・大全

目录

    • 1、对全部表单项的校验
    • 2、校验指定字段
    • 3、自定义函数校验表单
    • 4、一行内多个输入框的校验

element-ui 官网

element-ui 表单校验的规则如下:

<属性名>: [
	{ 
		required: true,// 是否必填(若有label则在其左上角显示红点,否则不显示必填标志),可选。
		type: 'date',// 限制输入的数据类型,可选。
		min: 3,// 当输入的是数值时,限制输入的最小值,可选。
		max: 5,// 当输入的是数值时,限制输入的最大值,可选。
		pattern: /^\d+\.\d+\.\d+$/,// 正则表达式,可选。
		message: "请使用 x.x.x 格式编号",// 错误时提示信息,必须。
		trigger: ['change', 'blur']// 触发校验的事件,必须。监听单一事件用字符串,监听多个事件用数组
	},
	// ...
]

1、对全部表单项的校验

<template>
<form ref="formRef" :model="form" :rules="rules" hide-required-asterisk class="base-form" :label-width="120">
	<el-form-item label="编码:" prop="code">
		<el-input v-model="form.code" placeholder="请输入编码" clearable/>
	el-form-item>
	<el-form-item label="地址" prop="address">
		<el-select v-model="form.address" placeholder="请选择一个城市" clearable>
			<el-option label="上海" value="shanghai" />
			<el-option label="北京" value="beijing" />
		el-select>
    el-form-item>
	<el-form-item label="月份:" prop="moth">
		<el-input v-model="form.moth" placeholder="请输入月份" clearable/>
	el-form-item>
	<el-form-item label="日期" prop="date">
		<el-date-picker v-model="form.date" type="date" placeholder="请选择日期" clearable/>
	el-form-item>
	<el-form-item label="成员:" prop="members">
		<el-checkbox-group v-model="form.members">
        	<el-checkbox label="一号" name="members" />
        	<el-checkbox label="二号" name="members" />
        	<el-checkbox label="三号" name="members" />
		el-checkbox-group>
    el-form-item>
	<el-form-item label="手机号:" prop="phone">
		<el-input v-model="form.phone" placeholder="请输入手机号" clearable/>
	el-form-item>
	<el-form-item>
		<el-button @click="submit(formRef)">保存el-button>
    el-form-item>
form>
template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'

const formRef = ref(null)

interface RuleForm {
    code: string
   	address: string
    moth: string | number
	date: Date | string
	members: string[]
	phone: string
}

const form = reactive<RuleForm>({
	code: '',
	address: '',
    moth: '',
	date: '',
	members: []
	phone: '',
})

// 表单校验
const rules = reactive<FormRules<RuleForm>>({
	// 失焦触发校验
	code: [{ required: true, message: '请输入编码', trigger: 'blur' }],
	// 值改变时触发校验
	address: [{ required: true, message: '请选择一个城市', trigger: 'change' }],
	// 包含最大值和最小值
	moth: [
		{ required: true, message: '请输入月', trigger: 'blur' },
		{ min: 1, max: 12, message: '请输入1~12月中的一个', trigger: 'blur' },
	],
	// 带类型的校验 - 类型为日期
	date: [{ type: 'date', required: true, message: '请输入日期', trigger: 'change' }],
	// 带类型的校验 - 类型为数组
	members: [{ type: 'array', required: true, message: '请选择成员', trigger: 'change' }],
	// 带正则表达式的校验
    phone: [
    	{ required: true, message: '请输入手机号', trigger: 'blur' },
    	{ pattern: /^(13[0-9]|15[0-9]|17[0-9]|18[0-9]|19[0-9])[0-9]{8}$/, message: '请输入正确的手机号', trigger: 'blur' },
    ],
})

// 提交 - 对整个表单进行校验
const submit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return
	await formEl.validate((valid, fields) => {
		if (valid) {
			console.log('submit!')
		} else {
			console.log('error submit!', fields)
		}
	})
}
script>

2、校验指定字段

<template>
<form ref="formRef" class="base-form" :model="form" :label-width="120" :rules="rules" hide-required-asterisk>
	<el-form-item label="编码:" prop="code">
		<el-input v-model="form.code" autocomplete="off" clearable @input="validateSelect" @keyup.enter="validateSelect"/>
	el-form-item>
form>
template>
<script setup lang="ts">
import { ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'

const formRef = ref(null)

interface RuleForm {
    code: string
}

const form = ref<RuleForm>({
    code: '',
})

// 表单校验
const rules = reactive<FormRules<RuleForm>>({
    code: [{ required: true, message: '请填写编码', trigger: 'blur' }],,
})

// 校验指定字段
const validateSelect = () => {
	formRef.value!.validateField('selectValue')
}
script>

3、自定义函数校验表单

<template>
<form ref="formRef" class="base-form" :model="form" :label-width="120" :rules="rules" hide-required-asterisk>
	<el-form-item label="手机号:" prop="phoneNumber">
		<el-input v-model="form.phoneNumber" autocomplete="off" clearable/>
	el-form-item>
form>
template>
<script setup lang="ts">
import { ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'

const formRef = ref(null)

interface RuleForm {
    phoneNumber: string
}

const form = ref<RuleForm>({
    phoneNumber: '',
})

// 自定义校验 - 手机号
const checkPhoneNumber = (rule: any, value: any, callback: any) => {
	const pattern = /^(13[0-9]|15[0-9]|17[0-9]|18[0-9]|19[0-9])[0-9]{8}$/
	if(!value) {
		callback(new Error('请输入手机号'))
	} else if(!pattern.test(val)) {
		callback(new Error('请输入正确的手机号'))
	} else {
		callback()
	}
}

// 表单校验
const rules = reactive<FormRules<RuleForm>>({
    phoneNumber: [{ validator: checkPhoneNumber, trigger: 'blur' }],,
})
script>

4、一行内多个输入框的校验

<template>
<form ref="formRef" class="base-form" :model="form" :label-width="120" :rules="rules" hide-required-asterisk>
	<el-form-item class="form-row" label="测试:" prop="test">
        <section class="form-col">
            1 <el-input class="ml-5" v-model="form.test[0]" placeholder="第1项" clearable/>
        section>
        <section class="form-col">
            2 <el-input class="ml-5" v-model="form.test[1]" placeholder="第2项" clearable/>
        section>
    el-form-item>
form>
template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'

// 表单
const formRef = ref<FormInstance>()

interface RuleForm {
    test: string[]
}

const form = ref<RuleForm>({
    test: [],
})

const checkTest =  = (rule: any, value: any, callback: any) => {
    const [oneStr, twoEnd] = form.value.coordinate
    const pattern1 = /^[EWew]?[+-]?([0-9]|[1-8][0-9]|90)(\.\d+)?$/
    const pattern2 = /^[NSns]?[+-]?([0-9]|[1-9][0-9]|1[0-7][0-9]|180)(\.\d+)?$/

    if (oneStr && twoEnd && pattern1.test(oneStr) && pattern2.test(twoEnd)) {
        callback()
    } else {
    	!oneStr && !twoEnd && callback(new Error('请输入所有项'))
	    !oneStr && callback(new Error('请输入第1项'))
	    !twoEnd && callback(new Error('请输入第2项'))
	    !(pattern1.test(oneStr)) && callback(new Error('请输入正确的第1项'))
	    !(pattern2.test(twoEnd)) && callback(new Error('请输入正确的第2项'))
	    !(pattern1.test(oneStr)) && !(pattern2.test(twoEnd)) && callback(new Error('请输入正确的项'))
    }
}

const rules = reactive<FormRules<RuleForm>>({
    test: [{ validator: checkTest, trigger: 'blur' }],
})
script>

你可能感兴趣的:(element-ui,element-plus)