element-ui提供了一套表单验证规则,非常方便,但也要注意一些地方。
html
<el-form :inline="true" :model="newReg" :rules="rules" ref="newReg" :label-width="'60px'">
<el-form-item label="付款人:" prop="payer">
<el-input v-model="newReg.payer" placeholder="请输入付款人姓名/手机号码/UID"></el-input>
</el-form-item>
<el-form-item label="收款人:" prop="payee">
<el-input v-model="newReg.payee" @blur="showUserInfo" placeholder="请输入收款人姓名/手机号码/UID"></el-input>
</el-form-item>
<el-alert title="收款人详细信息" type="info" :closable="false" v-if="alertUserInfo" class="modalUserDetails">
<p>姓名:{{payeeInfo.lastName}}</p>
<p>UID:{{payeeInfo.userId}}</p>
<p>手机号码:{{payeeInfo.mobile}}</p>
<p><el-button size="mini" type="text">查看详情</el-button></p>
</el-alert>
<el-form-item label="币种:">
<el-select v-model="newReg.productCode">
<el-option v-for="i in currencyList" :label="i" :key="i" :value="i"></el-option>
</el-select>
</el-form-item>
<el-form-item label="数量:" prop="quantity">
<el-input v-model.number="newReg.quantity" placeholder="请输入划拨数量"></el-input>
</el-form-item>
<el-form-item label="备注:" prop="remarks">
<el-input v-model="newReg.remarks" placeholder="请输入备注(2-50)" type="textarea" :autosize="{ minRows: 4, maxRows: 4}" :maxlength="50"></el-input>
</el-form-item>
<p></p>
<el-form-item>
<el-button @click="submitForm('newReg')" class="ModalBtn" type="primary">确定</el-button>
</el-form-item>
</el-form>
js
data(){
var newReg1 = (rule, value, callback) => {
if (this.trimStr(value).length<2) {
callback(new Error('不能少于两个字符'));
} else {
callback();
}
};
var newReg2 = (rule, value, callback) => {
var value=this.trimStr(value);
if (value!=parseFloat(value)) {
callback(new Error('只能是数字'));
} else if(value<=0){
callback(new Error('不能为负数'));
}else{
callback();
}
};
return{
newReg:{ //新建划拨
payer:"", //付款人
payee:"", //收款人
productCode:"USDT", //币种
quantity:"", //数量
remarks:"", //备注
},
rules: {
payer: [ { validator: newReg1, trigger: 'blur' } ],
payee: [ { validator: newReg1, trigger: 'blur' } ],
quantity: [{ validator: newReg2, trigger: 'blur' }],
remarks: [{ validator: newReg1, trigger: 'blur' },]
},
}
}
*其中需要特别注意的就是 rules 中的 key 必须要与 newReg 中的 key 相同,否则会出现 value 一直是 undefined ,明明有值,却总是验证不通过