JavaScript简单表单验证:用户名密码是否为空
form表单代码<form name="form1" method="post" action="">用户名:<input name="user" type="text" id="user">密码:<input name="pwd" type="password" id="pwd"><input type="button" name="button...
·
示例一
form表单代码
<form name="form1" method="post" action="">
用户名:<input name="user" type="text" id="user">
密码:<input name="pwd" type="password" id="pwd">
<input type="button" name="button" value="登陆" onclick="check()">
<input type="reset" value="重置">
</form>
自定义JavaScript函数check()
<script language="javascript">
function check(){
if(form1.user.value==""){
alert("请输入用户名!");
form1.user.focus();
return;
} else if (form1.pwd.value=="") {
alert("请输入密码!");
form.pwd.focus();
return;
} else {
form1.submit();
}
}
</script>
示例二
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="" name="my_form" onsubmit="return check_form(this)">
用户名:<input type="text" name="username"><br> 密码:
<input type="text" name="password">
<input type="submit" value="登录"><input type="reset" value="清空">
</form>
<script>
function check_form(form) {
if (form.username.value == "") {
alert("用户名为空")
form.username.focus();
return false;
}
if (form.password.value == "") {
alert("密码为空")
form.password.focus();
return false;
}
return true;
}
</script>
</body>
</html>
这里只是一个简单的JavaScript表单验证,还可以加入正则表达式扩展为更合理的验证;
更多推荐



所有评论(0)