表单验证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'

const ruleFormRef = ref<FormInstance>()

interface RuleForm {
name: string
region: number
}

const ruleForm = reactive<RuleForm>({
name: 'Hello',
region: ''
})

const confirmRules = (_rule: any, _value: any, callback: any) => {
if (ruleForm.name!=='zs') {
// 不通过回调
callback(new Error('name不能等于zs'))
} else {
// 通过回调
callback()
}
}

const rules = reactive<FormRules<RuleForm>>({
name: [
{ required: true, message: '必传', trigger: 'blur' },
{ min: 3, max: 5, message: '取值范围', trigger: 'blur' },
{ validator: confirmRules, trigger: 'blur' },
],
})

type的类型:

  • string: Must be of type string. This is the default type.
  • number: Must be of type number.
  • boolean: Must be of type boolean.
  • method: Must be of type function.
  • regexp: Must be an instance of RegExp or a string that does not generate an exception when creating a new RegExp.
  • integer: Must be of type number and an integer.
  • float: Must be of type number and a floating point number.
  • array: Must be an array as determined by Array.isArray.
  • object: Must be of type object and not Array.isArray.
  • enum: Value must exist in the enum.
  • date: Value must be valid as determined by Date
  • url: Must be of type url.
  • hex: Must be of type hex.
  • email: Must be of type email.
  • any: Can be any type.