简单的表单验证
效果图:
失焦验证,点击按钮再次验证,验证通过切换

html:
<div class="test"> <div class="content1" v-if="xyb == 0"> 用户注册 <input type="text" name="" id="name" v-model="Data.name" placeholder="用户名" @blur="aa" /> <span class="name_msg">{{ check.aname }}</span> <input type="text" name="" id="num" v-model="Data.num" placeholder="验证码" @blur="bb" /> <span class="num_msg">{{ check.anum }}</span> <div class="btn" @click="next">下一步</div> </div> <div class="content2" v-if="xyb == 1"> 设置密码 <input type="password" name="" id="pwd1" placeholder="请输入密码" v-model="Data.psw1" @blur="cc" /> <span class="psw1_msg">{{ check.apsw1 }}</span> <input type="password" name="" id="pwd2" v-model="Data.psw2" placeholder="再次输入密码" @blur="dd" /> <span class="psw2_msg">{{ check.apsw2 }}</span> <div class="btn">提交</div> </div> </div>
js:
export default { data() { return { xyb: "", Data: { name: "", num: "", psw1: "", psw2: "", }, check: { aname: "", anum: "", apsw1: "", apsw2: "", }, }; }, methods: { aa() { if (!this.Data.name) { this.check["aname"] = "请输入用户名"; return false; } else if ( !/^[a-zA-Z0-9_-]{4,6}$/.test(this.Data.name) ) { this.check["aname"] = "用户名为4~6位英文、数字"; return false; } else { this.check["aname"] = ""; return true; } }, bb() { if (!this.Data.num) { this.check["anum"] = "请输入验证码"; return false; } else if (!/^[0-9]{4}$/.test(this.Data.num)) { this.check["anum"] = "验证码为4位数字"; return false; } else { this.check["anum"] = ""; return true; } }, next() { if (!this.bb() == true && !this.aa() == true) { this.check["aname"] = "请输入正确的用户名"; this.check["anum"] = "请输入正确的验证码"; } else if (!this.aa() == true) { this.check["aname"] = "请输入正确的用户名"; } else if (!this.bb() == true) { this.check["anum"] = "请输入正确的验证码"; } else { this.xyb = 1; } }, cc() { if (!this.Data.psw1) { this.check["apsw1"] = "请设置密码"; return false; }else if (!/^[0-9]{4}$/.test(this.Data.psw1)) { this.check["apsw1"] = "密码为4位数字"; return false; }else { this.check["apsw1"] = ""; return true; } }, dd() { if (this.cc() == false) { this.check["apsw1"] = "请设置密码"; return false; }else if (!(this.Data.psw1 === this.Data.psw2)){ this.check["apsw2"] = "两密码输入不一致"; return true; }else { this.check["apsw2"] = ""; return true; } }, }, };
css:
.name_msg,
.psw1_msg,
.psw2_msg,
.num_msg {
height: 15px;
font-size: 14px;
color: #de2013;
}
.btn {
color: #fff;
margin-bottom: 10px;
display: flex;
justify-content: center;
align-items: center;
font-size: 16px;
width: 80px;
height: 30px;
background-color: #de2013;
border-radius: 5px;
cursor: pointer;
}
.content1,
.content2 {
height: 200px;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
}
.test {
display: flex;
flex-direction: column;
justify-content: center;
width: 500px;
background-color: rgb(169, 218, 218);
}
input {
outline: none;
width: 200px;
height: 25px;
}

浙公网安备 33010602011771号