一、使用插件async-validatorvue
async-validator 地址:https://github.com/yiminghe/async-validatorgit
二、示例(vue+element-ui)github
<el-form :model="numberValidateForm" ref="numberValidateForm" label-width="100px" class="demo-ruleForm">
<el-form-item label="年齡" prop="age" :rules="[ { required: true, message: '年齡不能爲空'}, { type: 'number', message: '年齡必須爲數字值'} ]"
>
<el-input type="age" v-model.number="numberValidateForm.age" autocomplete="off"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('numberValidateForm')">提交</el-button>
<el-button @click="resetForm('numberValidateForm')">重置</el-button>
</el-form-item>
</el-form>
<script> export default { data() { return { numberValidateForm: { age: '' } }; }, methods: { submitForm(formName) { this.$refs[formName].validate((valid) => { if (valid) { alert('submit!'); } else { console.log('error submit!!'); return false; } }); }, resetForm(formName) { this.$refs[formName].resetFields(); } } } </script>
注意校驗書寫格式:element-ui
{ required: true, message: '年齡不能爲空'},
{ type: 'number', message: '年齡必須爲數字值'}
像校驗郵箱、數值類型類型時,多行配置校驗規則。