问题:表单怎么在输入后立即验证,而不是提交后再验证那么不方便(网上搜到的要么是模棱两可,要么是残缺不全…)
方法:鉴于此,加上我个人的理解(注释)在上面。
如果帮助到您,顶一下 ヾ(≧O≦)〃嗷~
截图:
代码:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户注册</title>
<!-- 此处引用外部css样式 -->
<link rel="stylesheet" href="css/style.css" />
<script type="text/javascript">
//及时验证用户名
function checkuse(){
//在每个函数中定义check变量是为了在表单提交后,能够逐个验证每个函数是否通过,很好很好。(以下同理)
var check;
var username = document.getElementById("username").value;
if (username.length > 18 || username.length < 6) {
alert("用户名输入不合法,请重新输入!");
//此处甚妙,既然你在此处输入错误,那么按理说当然要在此处继续输入了。(在此处继续获取焦点!)
document.getElementById("username").focus();
check = false;
} else {
document.getElementById("checktext1").innerHTML = "* 用户名由6-18位字符组成 √";
check = true;
}
return check;
}
//利用正则表达式判断密码符合否
function checkpwd() {
var check;
var reg = /[^A-Za-z0-9_]+/;
var regs = /^[a-zA-Z0-9_\u4e00-\u9fa5] + $ /;
var password = document.getElementById("password").value;
if (password.length < 6 || password.length > 18 || regs.test(password)) {
alert("密码输入不合法,请重新输入!");
document.getElementById("password").focus();
check = false;
} else {
document.getElementById("checktext2").innerHTML = "* 密码由6-18位字符组成,且必须包含字母、数字和标点符号 √";
check = true;
}
return check;
}
//验证密码是否不一致!
function checkpwdc() {
var check;
var password = document.getElementById("password").value;
var pwdc = document.getElementById("pwdc").value;
if (password != pwdc) {
alert("两次输入密码不一致,请重新输入!");
document.getElementById("pwdc").focus();
check = false;
} else {
document.getElementById("checktext3").innerHTML = "* 请再次输入你的密码 √";
check = true;
}
return check;
}
//提交时验证用户类别
function checkut(){
var check;
if(document.getElementById("selUser").selectedIndex == 0)
{
alert("请选择用户类型!");
document.getElementById("selUser").focus();
check = false;
}else{
d