js 实现简单的注册校验功能(vue)
做一个小练习—-注册功能的校验,校验要求为:1)用户名、密码、确认密码不能为空;
2)密码由大写字母、小写字母和数字组成且长度区间为\[8,16\];
3)确认密码应和密码一致。
不符合要求给出提示信息。
思路:通过监听输入框的blur事件来进行输入内容校验,输入不合格在相应的input后面进行提示,提示使用span标签。
实现代码:
<template>
<div class="container">
<form action="" method="">
<label>用户名: <input type="text" placeholder="请输入用户名" v-model="name" @blur="getName"><span>{
{mesName}}</span></label>
<label>密码: <input type="password" placeholder="请输入密码" v-model="pwd" @blur="getPwd"><span>{
{mesPwd}}</span></label>
<label>确认密码:<input type="password" placeholder="请再次输入密码" v-model="pwd2"><span>{
{mesPwd2}}</span></label>
<button @click="toLogin" @click.prevent >注册</button>
</form>
</div>
</template>
<script>
export default {
name: 'login',
data () {
return {
name: '',
pwd: '',
pwd2: '',
mesName: '', //存储用户名校验提示内容
mesPwd: '', //存储密码校验提示内容
mesPwd2: '', //存储确认密码校验提示内容
}
},
methods: {
// 校验用户名输入是否为空
getName() {
if (!this.name) {
this.mesName = '用户名不能为空'
} else {
this.mesName = ''
}
},
// 校验密码输入是否符合要求
getPwd() {
var pat = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{6,14}$/;
if (!this.pwd) {
this.mesPwd = '密码不能为空'
} else if (!pat.test(this.pwd)) {
this.mesPwd = '密码至少包含小写字母、大写字母和数字且长度不能低于六位'
} else {
this.mesPwd = ''
}
},
// 校验确认密码是否和密码一致
getPwd2() {
if (!this.pwd2) {
this.mesPwd2 = '请再次输入密码'
} else if (this.pwd2 != this.pwd) {
this.mesPwd2 = '前后密码不一致'
} else {
this.mesPwd2 = ''
}
},
//点击注册按钮
toLogin() {
if (!this.mesName && !this.mesPwd && !this.mesPwd2) {
alert("注册成功")
}else {
alert("请按要求填写全部信息")
}
}
}
}
</script>
<style scoped>
.container{
width: 600px;
/* border: 1px solid grey; */
padding: 20px;
margin: 0 auto;
}
label {
display: block;
margin-bottom: 15px;
}
span {
font-size: 12px;
color: red;
}
button {
margin-left: 100px;
}
</style>
还没有评论,来说两句吧...