Skip to content

表单校验规则

NaiveUI的表单组件支持校验规则,但是这些校验规则是通过FormRules类型的对象来定义的,而且这个对象的定义方式比较繁琐,所以我们对其进行了封装,提供了一个Rules类,内置了很多校验规则,并且可以通过链式调用的方式来拼接多条校验规则。

示例代码

vue
<template>
    <n-form
        ref="formRef"
        :model="form"
        :rules="rules"
    >
    </n-form>
</template>
<script setup lang="ts">
    import { reactive, ref, toRef } from 'vue'
    import type { FormInst, FormRules } from 'naive-ui'
    import { useResetableData } from '@/hooks/common/use-reset-ref'
    import { Rules } from '@/utils'
    const form = useResetableData<UserType>({
        //...
    })
    const rules: FormRules = {
        name: new Rules().required().value,
        password: new Rules().required('请输入密码').value,
        confirmPwd: new Rules()
            .required('请输入密码再次确认')
            .eq(toRef(form, 'password'), '两次输入的密码不一致').value,
        phone: new Rules().required().phone().value,
        age: new Rules()._pint('年龄只能填入正整数').lt(150,'年龄不能大于150岁').gt(0, '年龄不能小于0').value,
        email: new Rules().email().value,
        remark: new Rules().maxLength(100).push({
            validator(rule: FormItemRule, value: string) {
                if (!value || contentIsEmpty(value)) {
                    return new Error('请输入内容')
                }
                return true
            },
            trigger: ['blur']
        }).value,
    }
</script>
<template>
    <n-form
        ref="formRef"
        :model="form"
        :rules="rules"
    >
    </n-form>
</template>
<script setup lang="ts">
    import { reactive, ref, toRef } from 'vue'
    import type { FormInst, FormRules } from 'naive-ui'
    import { useResetableData } from '@/hooks/common/use-reset-ref'
    import { Rules } from '@/utils'
    const form = useResetableData<UserType>({
        //...
    })
    const rules: FormRules = {
        name: new Rules().required().value,
        password: new Rules().required('请输入密码').value,
        confirmPwd: new Rules()
            .required('请输入密码再次确认')
            .eq(toRef(form, 'password'), '两次输入的密码不一致').value,
        phone: new Rules().required().phone().value,
        age: new Rules()._pint('年龄只能填入正整数').lt(150,'年龄不能大于150岁').gt(0, '年龄不能小于0').value,
        email: new Rules().email().value,
        remark: new Rules().maxLength(100).push({
            validator(rule: FormItemRule, value: string) {
                if (!value || contentIsEmpty(value)) {
                    return new Error('请输入内容')
                }
                return true
            },
            trigger: ['blur']
        }).value,
    }
</script>
方法名定义说明
requiredrequired(
message: string = '不能为空',
trigger: ValidationTrigger[] = ['input', 'blur', 'change'] )
必填
注意以下规则将在值有效的情况下才生效,不额外做非空校验。
非空校验请添加required规则
minLengthminLength(
length: number,
message: string = `长度不能小于${length}位`,
trigger: ValidationTrigger[] = ['input', 'blur'])
最小长度
maxLengthmaxLength(
length: number,
message: string = `长度不能超过${length}位`,
trigger: ValidationTrigger[] = ['input', 'blur'])
最大长度
lengthlength(
length: number,
message: string = `字符长度需要等于${length}位`,
trigger: ValidationTrigger[] = ['input', 'blur'])
指定长度
eqeq(
compareValue: Ref<string> | string | number,
message: string ='',
trigger: ValidationTrigger[] = ['input', 'blur'])
与指定值相等。
注意,如果是和一个响应式数据比较,需要使用toRef方法,如:toRef(resetPwdForm, 'newPwd')
如果是和一个固定数值比较,直接传入即可,如:123
gtgt(
compareValue: Ref<string> | string | number,
message: string ='',
trigger: ValidationTrigger[] = ['input', 'blur'])
大于指定值。
注意,如果是和一个响应式数据比较,需要使用toRef方法,如:toRef(resetPwdForm, 'newPwd')
如果是和一个固定数值比较,直接传入即可,如:123
gte大于等于指定值。用法同gt
lt小于指定值,用法同gt
lte小于等于指定值,用法同gt
_int_int(
message: string = `必须是整数`,
trigger: ValidationTrigger[] = ['input', 'blur'])
是整数
_pint是正整数,用法同_int
_natural是自然数:0 和 正整数,用法同_int
_number是数字,用法同_int
_pnumber是正数,用法同_int
_zpnumber是正数和0,用法同_int
_boolean是布尔类型值,支持0、1、true、false
phonephone(
message: string = `手机号格式不正确`,
trigger: ValidationTrigger[] = ['input', 'blur'])
手机号
emailemail(
message: string = `邮箱格式不正确`,
trigger: ValidationTrigger[] = ['input', 'blur'])
邮箱
idcardidcard(
message: string = `身份证格式不正确`,
trigger: ValidationTrigger[]= ['input', 'blur'])
身份证校验
letterNumberletterNumber(
message: string = `仅支持字母和数字`,
trigger: ValidationTrigger[]= ['input', 'blur'])
字母和数字校验
commonCharcommonChar(
message: string = `检测到不支持的字符`,
trigger: ValidationTrigger[]= ['input', 'blur'])
仅支持常见字符,包含大小写 、数字、_、 -,
规则在constants/regexp中设定
regexregex(
regex: RegExp
message: string,
trigger: ValidationTrigger[]= ['input', 'blur'])
根据指定的正则表达式进行校验
pushpush(rule: FormItemRule)追加自定义校验规则,参考naiveui文档
deletedelete(index: number)删除第几条规则