JavaScript之表單驗證(2)(Regex)__JAVA
來源:互聯網
上載者:User
<html>
<head>
<title>damel14</title>
<script>
function checkName(){
var usernameObj = document.forms[0].username;
var username = usernameObj.value;
//var username = document.forms[0].username.value;
var reg = /^\s*$/;//不可為空
if(reg.test(username)){
alert("使用者名稱不可為空");
usernameObj.focus();
usernameObj.select();
return false;
}
reg=/^\w{5,10}$/;//必須是數字字母底線長度在5-10之間
if(!reg.test(username)){
alert("使用者名稱長度5-10(數字,字母,底線)");
usernameObj.focus();
usernameObj.select();
return false;
}
return true;
}
function checkPass(){
var passObj = document.forms[0].password;//擷取對象
var pass = passObj.value;
//var pass = document.forms[0].password.value;
var reg = /^\s*$/;//不可為空
if(reg.test(pass)){
alert("密碼不可為空");
passObj.focus();//擷取對象焦點
passObj.select();//選中對象
return false;
}
reg = /^[a-zA-Z\d]{6,12}$/;//密碼只能數字字母長度6-12
if(!reg.test(pass)){
alert("密碼只能數字字母長度6-12");
passObj.focus();
passObj.select();
return false;
}
return true;
}
function checkForm(){
return checkName()&&checkPass();
}
</script>
</head>
<body>
<form action="damel11.html" onSubmit="return checkForm()" name="myform">
使用者名稱:<input type="text" name="username"/>
</br>
密 碼:<input type="text" name="password" onClick="checkName()"/>
</br>
<input type="submit" value="確定"/>
</form>
</body>
<html>