vue 中 form 表单验证
程序员文章站
2022-04-25 15:47:40
...
地狱空荡荡,魔鬼在人间
首先使用 饿了么的表单代码
<el-form :model="loginForm" :rules="loginRules" class="card-box login-form" label-position="left" label-width="0px" ref="loginForm">
<el-form-item prop="username">
<el-input name="username" placeholder="账户" type="text" v-model="loginForm.username"></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input @keyup.enter.native="handleLogin" name="password" placeholder="密码" type="password" v-model="loginForm.password"></el-input>
</el-form-item>
<el-form-item>
<el-button @click.native.prevent="handleLogin" style="width:100%;" type="primary">
登录
</el-button>
</el-form-item>
</el-form>
然后在 data 中绑定需要验证的规则
data() {
const validatePass = (rule, value, callback) => {
if (value.length < 5) {
callback(new Error('密码不能小于5位'));
} else {
callback();
}
};
return {
loginForm: {
username: 'admin',
password: 'admin'
},
loginRules: {
username: [{required: true, message: '账户不能为空', trigger: 'blur'},
{min: 3, max: 40, message: '长度在 3 到 20 个字符', trigger: 'blur'}],
password: [{required: true, trigger: 'blur', validator: validatePass}]
},
}
},