您的位置:首页 > 其它

【网页设计】验证表单是否为空

2014-11-16 12:01 246 查看
在做登录注册页面的时候,需要检测用户是否合法输入,其中重要的一条就是,验证表单的信息是否为空

下面以一个账号密码登录表单为例,说一下用Javascript的一个解决方案

 

JavaScript中的函数:

<script type="text/javascript">
function     validate()
{
if(document.myform.username.value=="")
{
alert("用户名不能为空.");
document.myform.username.focus();
return   false   ;
}
if(document.myform.password.value=="")
{
alert("密码不能为空.");
document.myform.password.focus();
return   false   ;
}

return true;
}
</script>


Htnl表单

<form action="load" method="post" name="myform" id="myform"  onsubmit="return validate()">
<input type="text" name="username" style="width:190px; height:26px;"/><br/>
<input type="password" name="password" style="width:190px; height:26px; margin-top:12px;"/><br/>
<input type="submit" value="登录" style="width:50px; height:30px; margin-top:8px;"/>
</form>


获取username的另外方式:

var username=document.getElememntByID('username').value;

设置焦点的另外方式:

document.getElementById("username").focus();

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: