When this article on how to use the form validation form of iview. Learn how to use the main form check (to check the length of the text, for example), as well as how to dynamically add validation rules and asynchronous verification.
1. Add form tag form is to be verified
<!--注意: ref/rules/model/prop等属性是必须的-->
<Form res="foemRef" :rules="formRules" :model="formData" v-if="liveNode">
<Row>
<!--正常校验-->
<Col>
<FormItem prop="name">
<Input v-model="formData.name"></Input>
</FormItem>
</Col>
<!--动态校验-->
<Col v-if="flag">
<FormItem prop="age">
<Input v-model="formData.age"></Input>
</FormItem>
</Col>
<!--异步校验-->
<Col>
<FormItem prop="asyName">
<Input v-model="formData.asyName"></Input>
</FormItem>
</Col>
</Row>
</Form>
2. Add validation rules
formRules: {
name: [
{required: true, message: "必输项不能为空", trigger: 'blur'},
{validator:(rule, value, cb)=>{lenValid(value, 30, cb)}, trigger: 'blur'}
],
age:[], // 注意因为age是根据条件判断是否必输,先留个坑
asyName: [ // 异步校验,使用change触发,即使不改变输入数据也会在提交数据的时候自动校验一次
{validator:(rule, value, cb)=>{asyValid(value, cb)}, trigger: 'change'}
]
}
3. The calibration method
// 校验输入的字符长度
function lenValid(str, num, cb){
if(str){
let len = getLen(str)
if(len > num){
return cb(new Error('Too Long...'))
}
}
cb()
}
// 获取字符长度
function getLen(str){
let len = 0
if(str){
str = str + '' // to string
for(let i=0; i<str.length; i++){
let c = str.charCodeAt(i)
if((c >= 0x0001 && c <= 0x007e) || (0xff60 < = c && c <= 0xff9f)){
len++ // 单字节
}else{
len += 3 // 汉字
}
}
}
return len
}
4. dynamically add validation rules
Sometimes a need to dynamically switch input box, such as: age field above, when the display is losing items, non-hidden when losing this time dynamically changes validation rules
this.liveNode = flase // 先抹去Form,等校验规则修改后在重新渲染
if(this.flag){
this.formRules.age.unShift({required: true, message: '必输项'})
}else{
if(this.formRules.age.length > 0){
this.formRules.age.shift()
}
}
this.liveNode = true // 重新渲染Form
5. Asynchronous check
Sometimes the need to input content asynchronously in the background check
// 异步校验 - 成败都要有回调函数,校验失败抛出异常
function asyValid(value, cb){
let param = {asyName: value} // 将需要校验的值作为参数
$http(url,action,param,(res)=>{
cb()
},(err)=>{
cb(new Error(err.data.message))
})
}