正则表达式验证表单案例如下:
HTML: 在input标签外写一个label标签的作用是点击label标签input标签内的光标就会出现,然后在input标签内加入placeholder元素在文本框内显示出提示的字样,例如:2-16字符,建议英文字母!然后设置id名,再加上span标签,最后加上br标签换行以达到可观的效果。
<div class="container" id="dv">
<h3>注册页面</h3>
<label for="userName">账 户</label><input type="text" id="userName" placeholder="2-16字符,建议英文字母!"><span></span><br/>
<label for="phone">手 机</label><input type="text" id="phone" placeholder="请输入真实有效的手机号码"><span></span><br/>
<label for="e-mail">邮 箱</label><input type="text" id="e-mail" placeholder="请输入正确的邮箱!"><span></span><br/>
<label for="password">密 码</label><input type="text" id="password" placeholder="密码必须是6-18位数字!"><span></span><br/>
<label for="ispassword">确认密码</label><input type="text" id="ispassword" placeholder="请再次确认密码!"><span></span><br/>
</div>
CSS:使用css设置表单的外形。
<style type="text/css">
body {
background: #ccc;
}
label {
width: 100px;
display: inline-block;
}
span {
color: red;
}
.container {
margin: 100px auto;
width: 400px;
padding: 50px;
line-height: 40px;
border: 1px solid #999;
background: #efefef;
}
span {
margin-left: 30px;
font-size: 12px;
}
.wrong {
color: red
}
.right {
color: green;
}
.defau {
width: 200px;
height: 20px;
}
.de1 {
background-position: 0 -20px;
}
</style>
JavaScript
//获取各类ID名
var userName = document.getElementById("userName");
var phone = document.getElementById("phone");
var mail = document.getElementById("e-mail");
var password = document.getElementById("password");
var ispassword = document.getElementById("ispassword");
//给我文本框,给我这个文本框相应的正则表达式,我把结果显示出来,加入checkInput在()里面加入文本框里面的文字input和正则表达式reg
function checkInput(input,reg) {
//文本框注册失去焦点的事件onblur
input.onblur=function () {
//用if..else来判断在文本框内输入的字符是否符合reg
//在if()里面加入reg.test(放入文本)
if(reg.test(this.value)){
this.nextElementSibling.innerText="正确了";
this.nextElementSibling.style.color="green";
}else{
this.nextElementSibling.innerText="让你得瑟,错了吧";
this.nextElementSibling.style.color="red";
}
};
}
//写入正则以检查输入在文本框内的字符是否符合
//账号
checkInput(userName,/^[a-zA-Z]{5,11}$/);
//手机
checkInput(phone,/^\d{5,11}$/);
//邮箱
checkInput(mail,/^[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}$/);
//密码
checkInput(password,/^\d{6,18}$/);
//判断ispassword是否与password 相同,相同则为正确否则显示"两次密码不一样";
ispassword.onblur = function(){
if(this.value == password.value){
this.nextElementSibling.innerText="正确了";
this.nextElementSibling.style.color="green";
}else{
this.nextElementSibling.innerText="两次密码不一样";
this.nextElementSibling.style.color="red";
}
}
总结: 正则表达式:又可以叫规则表达式.是由一定规则组成的的式子也是由一些元字符或者是限定符组成的式子,它作用是用来匹配字符串的,主要离不开if…else判断;注意:正则表达式主要靠经验和找规律,不要追求完美。
这是我所学到的JavaScript案例,所以我要分享给你们,希望可以帮助到你们。
以上就是我的分享,新手上道,请多多指教。如果有更好的方法或不懂得地方欢迎在评论区教导和提问喔!