JavaScript----正则验证用户名密码等正确
效果图
js
function $(id) {
return document.getElementById(id);
}
function checkUser() {
var uname = $("uname").value;
uname = uname.trim();
var userp = $("unameWarn");
userp.innerHTML = "";
var reg = /^[a-zA-Z][a-zA-Z0-9]{5}$/;
var reg = new RegExp("[a-zA-Z][a-zA-Z0-9]{5}");
if (reg.test(uname) == false) {
userp.innerHTML = "错误";
return false;
}
}
function checkPwd() {
var psw = $("psw").value;
psw = psw.trim();
var pswW = $("pswWarn");
var reg = /^[a-zA-Z0-9]{8,16}$/;
pswW.innerHTML = "";
if (reg.test(psw) == false) {
pswW.innerHTML = "错误";
return false;
}
}
function checkEmail() {
var email = $("email").value;
email = email.trim();
var emailW = $("emailWarn");
var reg = /^\w+@\w+(\.[a-zA-Z]{2,4}){1,2}$/;
emailW.innerHTML = "";
if (reg.test(email) == false) {
emailW.innerHTML = "错误";
return false;
}
}
function checkIp() {
var ip = $("ip").value;
ip = ip.trim();
var ipW = $("ipWarn");
var reg = /^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
ipW.innerHTML = "";
if (reg.test(ip) == false) {
ipW.innerHTML = "错误";
return false;
}
}
function checktel() {
var tel = $("tel").value;
tel = tel.trim();
var telW = $("telWarn");
var reg = /^[0](\d{3})(\-)(\d){7,8}$/;
telW.innerHTML = "";
if (reg.test(tel) == false) {
telW.innerHTML = "错误";
return false;
}
}
html
<form>
<table class="tab">
<tr>
<td>用户名:</td>
<td><input type="text" id="uname" placeholder="以字母开头,总长度为6" onblur="checkUser()"></td>
<td><span id="unameWarn"><span></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" id="psw" placeholder="8到16位字母或数字组成" onblur="checkPwd()"></td>
<td><span id="pswWarn"><span></td>
</tr>
<tr>
<td>电子邮箱:</td>
<td><input type="text" id="tel" placeholder="email格式你懂的" onblur="checkTel()"></td>
<td><span id="telWarn"><span></td>
</tr>
<tr>
<td>ip地址:</td>
<td><input type="text" id="email" placeholder="4段0-255的整数以点分隔构成" onblur="checkEmail()"></td>
<td><span id="emailWarn"><span></td>
</tr>
<tr>
<td>座机号码:</td>
<td><input type="text" id="ip" placeholder="4位区号-7位或8位数字" onblur="checkip()"></td>
<td><span id="ipWarn"><span></td>
</tr>
<tr>
<td colspan="3"><input type="reset" value="重置">
<input type="submit" value="提交" id="subbtn">
</td>
</tr>
</table>
</form>
css
.tab {
width: 320px;
margin: 20px auto;
height: 260px;
}
.tab tr td:first-child {
text-align: right;
}
.tab tr:last-child td {
text-align: center;
}