HTML代码:
<form action="index.html" method="post" id="myform">
<dl class="register_row">
<dt>Email地址:</dt>
<dd><input id="email" type="email" required="required" class="register_input" pattern="^\w+@\w+(\.[a-zA-Z]{2,3}){1,2}$"/></dd>
</dl>
<dl class="register_row">
<dt>设置昵称:</dt>
<dd><input id="nickName" type="text" class="register_input" required="required" pattern="[a-zA-Z0-9]{4,20}"/></dd>
</dl>
<dl class="register_row">
<dt>设定密码:</dt>
<dd><input id="pwd" type="password" class="register_input"required="required" pattern="[a-zA-Z0-9]{6,20}"/></dd>
</dl>
<dl class="register_row">
<dt>再输入一次密码:</dt>
<dd><input id="repwd" type="password" class="register_input" required="required" pattern="[a-zA-Z0-9]{6,20}"/></dd>
</dl>
<dl class="register_row">
<dt>性别:</dt>
<dd><input name="sex" id="man" type="radio" value="男" checked="checked"/> <label for="man">男</label></dd>
<dd> <input name="sex" id="woman" type="radio" value="女"/> <label for="woman">女</label></dd>
</dl>
<dl class="register_row">
<dt>所在地区:</dt>
<dd>
<select id="province" style="width:120px;">
<option>请选择省/城市</option>
</select>
</dd>
<dd>
<select id="city" style="width:130px;">
<option>请选择城市</option>
</select>
</dd>
</dl>
<div class="registerBtn"><input id="registerBtn" type="image" src="images/register_btn_out.gif"/></div>
</form>
JS代码:
$("#registerBtn").click(function(){
var email=document.getElementById("email");//这个只能是document对象
if(email.validity.valueMissing==true){
email.setCustomValidity("邮箱不能为空!");
return;
}
else if(email.validity.patternMismatch==true){
email.setCustomValidity("邮箱格式不正确!");
return;
}
else{
email.setCustomValidity("");
}
var name=document.getElementById("nickName");
if(name.validity.valueMissing==true){
name.setCustomValidity("昵称不能为空!");
return;
}
else if(name.validity.patternMismatch==true){
name.setCustomValidity("昵称必须是4-20位的英文和数字!");
return;
}
else{
name.setCustomValidity("");
}
var pwd=document.getElementById("pwd");
if(pwd.validity.valueMissing==true){
pwd.setCustomValidity("密码不能为空!");
return;
}
else if(pwd.validity.patternMismatch==true){
pwd.setCustomValidity("密码必须是6-20位的英文和数字!");
return;
}
else{
pwd.setCustomValidity("");
}
var rpwd=document.getElementById("repwd");
if(rpwd.validity.valueMissing==true){
rpwd.setCustomValidity("密码不能为空!");
return;
}
else if(rpwd.value!=pwd.value){
rpwd.setCustomValidity("两次输入的密码不一样!");
return;
}
else{
rpwd.setCustomValidity("");
}
var province=document.getElementById("#province");
if(province.value=="请选择省/城市"){
alert(1);
province.setCustomValidity("请选择省份!");
return;
}
else{
province.setCustomValidity("");
}
var city=document.getElementById("#city");
if(city.value=="请选择城市"){
city.setCustomValidity("选择城市不能为空!");
return;
}
else{
city.setCustomValidity("");
}
var us=$("#email").val();
var u=new User($("#nickName").val(),$("#pwd").val(),us,$("#province").val()+$("#city").val(),$("input [name='sex']").val());
users[us]=[u];
})
实现效果:
使用注意事项:
js验证元素注意顺序要与html元素的一致
来源:oschina
链接:https://my.oschina.net/u/4288069/blog/4008704