js中如何验证字符串相等

就是编写了一个表单的,提交时,用js验证两次输入密码是否相等,直接“==”行吗
而且要不相等时,再返回到注册页面

javascript中等于(==)可以判断值是否一致,恒等于(===)用以判断值与类型是否都一致。所以验证字符串是否相等可以使用==或===,但是在涉及到变量类型时需要注意==与===的区别。

下面给出验证字符串相等的实例演示:

1、创建Html元素

<div class="box">
<span>实例演示:点击按钮验证两次输入的密码是否一致</span><br>
<div class="content">
请输入密码:<input type="text" id="pwd1"><br>
请重复密码:<input type="text" id="pwd2">
    <input id='btn' type='button' onclick='test()' value='提交' />
</div>
</div>

2、设置css样式

div.box{width:300px;padding:20px;margin:20px;border:4px dashed #ccc;}
div.box>span{color:#999;font-style:italic;}
div.content{width:250px;margin:10px 0;padding:20px;border:2px solid #ff6666;}
input[type='button']{height:30px;margin:10px;padding:5px 10px;}
input[type='text']{width:100px;padding:5px 10px;margin:5px 0;border:1px solid #ff9966;}

3、编写jquery代码

function test(){
pwd1 = document.getElementById("pwd1").value;
pwd2 = document.getElementById("pwd2").value;
if(pwd1=="")
alert("请输入密码")
else if(pwd2=="")
alert("请重复密码")
else if(pwd2!==pwd1)
alert("两次密码输入不一致")
else
alert("验证通过")
}

4、观察效果

温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-05-08
很简单。。的写一个。。。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script type="text/javascript">

function checknumber(){
var userform = document.getElementsByName('userform')[0];
if(userform.acctno.value =='' || userform.pass1.value == '' || userform.pass2.value == '')
{
alert('信息为空!')
return false;
}
else{
if(userform.pass1.value == userform.pass2.value)
return ture;
else {
userform.pass2.value='';
userform.pass2.focus();
alert('密码输入错误!')
return false;}
}

}
</script>
</head>
<body>
<form method="get" action="" name="userform" onsubmit="return checknumber()">
<p>账号:
<input type="text" name="acctno" size="16">
<p>密码:
<input type="password" name="pass1" size="10">
<p>重复:
<input type="password" name="pass2" size="10">
<p>
<input type="submit" value="提交">
<input type="reset" value="重填">
</form>

</body>
</html>
第2个回答  2011-05-08
不可以哦,用equals方法。
if (pwd1.equals(pwd2)) {...}追问

不相等时怎样跳回注册页面呢,

追答

用window.location.href="index.html"。

本回答被提问者采纳

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网