首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Java Web开发 >

怎么用javascript来验证数据的有效性?

2011-12-25 
如何用javascript来验证数据的有效性??我写了一个简单的jsp实现了登录功能,可是有一个地方我一直没有搞清

如何用javascript来验证数据的有效性??
我写了一个简单的jsp实现了登录功能,可是有一个地方我一直没有搞清楚,我本来写了一段javascript来检查看用户是否在用户名和密码框中输入了数据,如果没有就发出一个提示。可是我自己试了,我在用户名和密码框中甚么也不填就直接按提交按钮,结果就报错了。高手帮帮我,看看这个是甚么原因。jsp代码如下(很简单):

<%@page   language= "java "   contentType= "text/html;charset=gb2312 "%>
<html>
<head>
<meta   http-equiv= "Content-Type "   content= "text/html;charset=gb2312 ">
<meta   http-equiv= "Content-Language "   content= "zh-cn ">
<title> 登录 </title>
<!--   javascript函数validateLogin(),用来验证是否填写了用户名和密码:-->
<script   language= "JavaScript "> <!--
        function   validateLogin(){
        var   strUsername   =   window.document.formLoign.username.value;
        var   strPassword   =   window.document.formLoign.password.value;
        if(strUsername   ==   " "){
                alert( "请输入用户名! ");
                return   false;
        }
        if(strPassword   ==   " "){
                alert( "请输入密码! ");
                return   false;
        }
}
-->
</script>
</head>

<body>
<!--   提交时调用JavaScript函数validateLogin()来验证是否填写了用户名和密码:-->
<form   method= "post "   name= "formLogin "   action= "verifylogin.jsp "   onSubmit= "javascript:return   validateLogin(); ">
<table   align= "center "   bgcolor= "#cccccc "   border= "0 "   cellPadding= "0 "   cellSpacing= "0 "   width= "275 ">
<tr>
<td   align= "right "   height= "48 "   vAlign= "bottom "   width= "94 "> 用户名: </td>
<td   height= "48 "   vAlign= "bottom "   width= "172 "> <input   name= "username "   maxLength= "20 "   size= "16 "> </td>
</tr>
<tr>
<td   align= "right "   height= "48 "     width= "94 "> &nbsp;密码: </td>
<td   height= "48 "   width= "172 "> <input   name= "password "   type= "password "   size= "16 "   maxLength= "20 "> </td>
</tr>
<tr>
<td   align= "right "   height= "48 "   width= "94 "> </td>
<td   height= "48 "   width= "172 ">
<input   name= "Submit "   type= "submit "   value= "提交 "> &nbsp;&nbsp;&nbsp;&nbsp;
<input   name= "Reset "   type= "reset "   value= "重置 ">  
</td>
</tr>
</table>
</form>
</body>
</html>

要怎么样做才能验证用户不填任何数据的情况??

[解决办法]
没你那么写过,我这样写的
<script language= "javascript ">
function Juge(form_insert)


{

if(form_insert.cLoginName.value == " ")
{
alert( "用户名不能输入空值 ");
form_insert.cLoginName.focus();
return (false);
}


if(form_insert.cLoginPwd.value == " ")
{
alert( "密码不能输入空值 ");
form_insert.cLoginPwd.focus();
return (false);
}
}

</script>
[解决办法]
这样就可以了:
<script language= "JavaScript "> <!--
function validateLogin(form){
var strUsername = form.username.value;
var strPassword = form.password.value;
if(strUsername == " "){
alert( "请输入用户名! ");
return false;
}
if(strPassword == " "){
alert( "请输入密码! ");
return false;
}
}
-->
</script>
<form method= "post " name= "formLogin " action= "verifylogin.jsp " onSubmit= "javascript:return validateLogin(this); ">

热点排行