【问题标题】:Creating a "simple" password validation field创建一个“简单”的密码验证字段
【发布时间】:2011-12-19 22:00:12
【问题描述】:

我正在尝试为网页创建密码字段。到目前为止,我有:

<form name="PasswordField" action="">
Password:
<input type="password" name="password">
<input type="button" value="Log in">
</form>

我知道很可怜。它不必花哨,我只需要它从文本框中“获取”密码并将其与页面密码匹配即可。我假设我可以使用 if-else?

*Code for get password from textbox when the "Log in" button is pressed here*
if (password = "rawr")
{alert('Correct!')}
else
{alert('Wrong Password')}

可悲的是,我一直在愚弄这个几个小时。我也尝试了函数,但(对我来说)这似乎也不起作用。

【问题讨论】:

  • 你应该看看正则表达式,你的脚本有错误,应该是password == "rawr" 和双等号
  • @ibu 正则表达式??不,这里没有必要。
  • 您遇到了什么具体问题?不知道如何获取输入框的值?
  • 您无法在页面中使用 javascript 检查密码并保留任何级别的安全性,因为任何想要查看的人都可以看到所有 JS。如果你想要安全,你必须从服务器检查密码。
  • @jfriend00 他标记了这个作业,所以我认为这只是表单的学习示例,而不是真实的站点。

标签: javascript forms passwords if-statement


【解决方案1】:

如果你走这条路,你需要将验证放在一个函数中,该函数在你的按钮的onclick 事件中被调用。另外要在js中访问密码&lt;input节点,你可以给它一个id并使用document.getElementById(id)。此外,= 是一个赋值运算符。使用== 进行比较:)

<head>
<script type="text/javascript">
function isValid(){
var password = document.getElementById('password').value;
if (password == "rawr")
{alert('Correct!')}
else
{alert('Wrong Password')}
}
</script>
</head>

<form name="PasswordField" action="">
Password:
<input type="password" id="password" name="password">
<input type="button" value="Log in" onclick="isValid();">
</form>

或者更简单的方法是将密码 DOM 节点作为参数传递给函数:

<head>
<script type="text/javascript">
function isValid(myNode){
var password = myNode.value;
if (password == "rawr")
{alert('Correct!')}
else
{alert('Wrong Password')}
}
</script>
</head>

<form name="PasswordField" action="">
Password:
<input type="password" id="password" name="password">
<input type="button" value="Log in" onclick="isValid(this);">
</form>

【讨论】:

  • 两者都工作得很好。谢谢!可以将头部中的脚本移动到文档中的其他任何位置吗?
  • @JoshI Np!它不是必需的,但通常/传统上您将 js 函数定义放在 &lt;head&gt; 标记中。如果需要在函数外运行js,需要适当放置
  • @Shredder 我认为您不应该对标有作业的问题给出如此完整的答案。一个提示,是的。但不是一个完整的答案。
【解决方案2】:

我使用了 jquery,这是我的解决方案:

<html>
<head>
    <script type="text/javascript" src="jquery-1.4.4.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("input[name='login']").click(function() {
                var s = $("input[name='password']").val();

                if(s == "rawr") {alert('Correct!')}
                else {alert('Wrong Password')}
            });
        });
    </script>

</head>

<body>
    <form name="PasswordField" action="">
    Password:<input type="password" name="password">
        <input type="button" value="Log in" name="login">
    </form>
</body>

</html>

【讨论】:

    【解决方案3】:

    这是你要找的吗?

    document.forms['PasswordField'].elements['password'].value
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-04
      • 2023-01-26
      • 2016-01-05
      • 2016-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-03
      相关资源
      最近更新 更多