Js实现简单的表单验证(小白篇)
程序员文章站
2022-05-31 14:11:08
...
用到的知识:
1、BOM对象基本操作
2、DOM对象基本操作
3、正则表达式的运用及函数
4、输入框光标事件
代码分析:
通过正则表达式基础和输入框光标事件,当鼠标移出输入框时引入函数,判断输入框输入的内容跟格式一不一样,将结果输出到DIV里显示,正确则用绿色显示,错误则用红色显示。
源码如下:
html部分:
<body>
<h2>会员注册</h2>
<form action="">
用  户  名:<input
type="text"
class="userName"
onchange="usName()"
/>
<div>
请输入4到20位由英文字母数字和下划线组成的字符串,且数组不能作为开头
</div>
<br />
密       码:<input
type="password"
class="passwrd1"
onchange="pswrd1()"
/>
<div>非空白字符6到20位</div>
<br />
确认密码:<input type="password" class="passwrd2" onchange="pswrd2()" />
<div>重新输入密码</div>
<br />
<input type="submit" value="提交" />
</form>
</body>
css样式部分:
div {
display: inline-block;
}
input[type="text"],
input[type="password"] {
width: 200px;
}
input[type="submit"] {
width: 100px;
height: 30px;
margin: 20px 0 0 120px;
}
js部分:
var usn = document.getElementsByClassName("userName");
var Pw1 = document.getElementsByClassName("passwrd1");
var Pw2 = document.getElementsByClassName("passwrd2");
var divUser = document.getElementsByTagName("div");
// console.log(divUser);
function usName() {
var usn1 = usn[0].value;
var usn2 = /[a-z A-Z _]{1}[a-z A-Z 0-9_]{3,19}/.test(usn1);
if (usn2) {
divUser[0].style.color = "green";
divUser[0].innerHTML = "格式正确";
} else {
divUser[0].style.color = "red";
divUser[0].innerHTML =
"格式错误,请输入4到20位由英文字母数字和下划线组成的字符串,且数组不能作为开头";
}
}
function pswrd1() {
var pvalue = Pw1[0].value;
var pvalue1 = /[a-z A-Z 0-9]{1}[a-z A-Z _ 0-9 ]{5,19}/.test(pvalue);
if (pvalue1) {
divUser[1].style.color = "green";
divUser[1].innerHTML = "格式正确";
} else {
divUser[1].style.color = "red";
divUser[1].innerHTML = "格式错误";
}
}
function pswrd2() {
var psvl1 = Pw1[0].value;
var psvl2 = Pw2[0].value;
if (psvl1 == psvl2) {
divUser[2].style.color = "green";
divUser[2].innerHTML = "密码正确";
} else {
divUser[2].style.color = "red";
divUser[2].innerHTML = "密码不一致";
}
}
效果图: