在iview 的 form表单中,可以通过设置rules 对表单的表单项的值在提交前进行是否合法判断。
官方示例的验证规则如下。
ruleValidate: { name: [ { required: true, message: 'The name cannot be empty', trigger: 'blur' } ], mail: [ { required: true, message: 'Mailbox cannot be empty', trigger: 'blur' }, { type: 'email', message: 'Incorrect email format', trigger: 'blur' } ], city: [ { required: true, message: 'Please select the city', trigger: 'change' } ], gender: [ { required: true, message: 'Please select gender', trigger: 'change' } ], interest: [ { required: true, type: 'array', min: 1, message: 'Choose at least one hobby', trigger: 'change' }, { type: 'array', max: 2, message: 'Choose two hobbies at best', trigger: 'change' } ], date: [ { required: true, type: 'date', message: 'Please select the date', trigger: 'change' } ], time: [ { required: true, type: 'string', message: 'Please select time', trigger: 'change' } ], desc: [ { required: true, message: 'Please enter a personal introduction', trigger: 'blur' }, { type: 'string', min: 20, message: 'Introduce no less than 20 words', trigger: 'blur' } ] }
有些人会习惯性复制第一个判断条件就用。那么就会出现意外情况。
<FormItem label="Gender" prop="gender"> <RadioGroup v-model="formValidate.gender"> <Radio :label="t.t1">Male</Radio> <Radio :label="t.t2">Female</Radio> </RadioGroup> </FormItem> data () { return { t:{t1:1,t2:0}, ... } } ... rules:{ gender: [ { required: true, message: 'Please select gender', trigger: 'change' } ], }
按上面的形式,radio的label的值是动态赋予的,然后又赋予了数字。gender的验证是过不了的。
让我们再看看其他表单项的验证规则,我们可以发现有些验证规则出现了type的属性。去表单验证规则,具体配置查看 async-validator的网页一看。type的默认值是string。所以数字无论如何都是过不了验证的。我们需要设置type=number,这样就能顺利通过验证了。