原生js的表单验证

最近在学原生的js,把一些练手的代码往博客放一放,权当积累经验,若有错漏,或是觉得浅显,大家不要见怪。

这是一个原生js编写的简单的表单验证:

<!DOCTYPE html>
<html>
<head>
<script>
function a(){
var b=document.getElementById('xxx1').value;
var c=document.getElementById('xxx2').value;
if(b!=c){
if(document.getElementById('99')!=null){//如果是第二次从id='xxx3'的input输入框中移开焦点,已添加过<p>标签,则不再添加新的<p>标签
return;
}
else{
var addp=document.createElement('p');
addp.id='99';
addp.setAttribute('style','color:red;font-size:12px;margin:5px 0px 10px 0px;');
var addptxt=document.createTextNode('两次密码输入不一致!');
addp.appendChild(addptxt);
document.getElementById('24').insertBefore(addp,document.getElementById('xxx3'));//在id='xxx3'的input输入框之前插入一个<p>标签,显示提示信息。
document.getElementById("xxx2").style.marginBottom="0px";
}
}
if(b==c){
var u=document.getElementById('99');
u.parentNode.removeChild(u);//密码修改到一致后,移除提示信息的<p>标签
document.getElementById("xxx2").style.marginBottom="10px";
}
}
</script>
</head>

<body>
<div id="24">
<input id='xxx1' style="100%;margin-bottom:10px;" type="password" name="xxx1" placeholder="请输入密码"/>
<input id='xxx2' style="100%;margin-bottom:10px;" type="password" name="xxx2" placeholder="确认密码" onblur="a()" />
<input id='xxx3' style="100%;margin-bottom:10px;" type="text" name="xxx3" placeholder="请输入邮箱" />
</div>
</body>
</html>

原文地址:https://www.cnblogs.com/chenyoumei/p/7448326.html