表单信息的验证-客户端的验证
表单信息的验证-客户端的验证
利用JavaScript脚本语言进行客户端的表单提交的信息进行验证,步骤:
1).在jsp页面的<head></head>中添加<script></script>脚本段,在该脚本段中定义信息判断的函数function1(),在函数中要获取提交的信息(两种方式获取表单提交的信息:1.在表单控件中添加ID值,应用的函数是:document.getElementById("ID-value")。2.根据每个表单控件的name来获取信息,应用的函数是:document.getElementById("name-value"))。
2).在定义的函数中进行相应的信息判断,例如:if......else......语句,while语句。
3).定义的function1()函数要有boolean型的返回值,当返回false时表单提交的信息不会提交到服务器端,当返回true时表单中提交的信息会提交到服务器端。
4).在<form>的属性中进行上面定义函数的注册<form onsubmit = "return function1()">
simple instance:
<html>
<head>
<title>formConfirm</title>
<script type = "text/javascript">
function validate()
{
var username = document.getElementById("username1");
var password = document.getElementById("password1");
var repassword = document.getElementById("repassword1");
if(username.value == "")
{
alert("username can't be permit blank");
return false;
}
if(password.value.length < 6)
{
alert("The length of password less than six");
return false;
}
if(repassword.value.length < 6)
{
alert("The length of password less than six");
return false;
}
if(password.value != repassword.value)
{
alert("password is not same with repassword");
return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit = "return validate()">
username:<input type = "text" name = "username" id = "username1"><br>
password:<input type = "password" name = "password" id = "password1"><br>
repassword:<input type = "password" name = "password" id = "repassword1"><br>
<input type = "submit" name = button value = "提交">
</form>
</body>
</html>