给表单加 :rules="LoginRules" item添加prop属性 username 和 password
data中定义LoginRules对象 以及validator校验规则
<template>
<div class="login-container">
<el-form ref="form"
:model="form"
:rules="LoginRules"
label-width="80px"
class="login-form">
<h2 class="login-title">登录</h2>
<el-form-item label="账号" prop="username">
<el-input v-model="form.username"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input v-model="form.password"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary"
@click="submitForm('form')">登录</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
export default {
data() {
var validateUserName = (rule,value,callback)=>{
value = value.trim();
const length = value && value.length;
const pwdReg = /^[a-zA-Z0-9_]+$/
if(value===""){
callback(new Error("请输入账号"))
}else if(length <4 || length>12){
callback(new Error("账号长度在4到12位之间"))
}else if(!pwdReg.test(value)){
callback(new Error("账号只能有英文或数字或下划线组成"))
}else{
callback()
}
}
return {
form:{
username:'',
password:''
},
LoginRules:{
username:[
{required:true,validator:validateUserName,trigger:['blur','change']}
],
password:[
{required:true,message:'请输入密码',trigger:['blur','change']}
]
}
};
},
components: {},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
},
}
}
</script>