javascript - 密码用html验证。获取请求重新加载页面而不是转到提交页面

标签 javascript html

我有一个带有 html 的帐户注册表。我有一个简单的密码验证检查,使用最少的 javascript。验证字段工作正常。如果密码不匹配,则在尝试点击提交按钮时会显示一条消息。如果它们确实匹配,则在单击提交时它会重新加载同一页面,而不是使用 GET 请求转到 results.html 页面。我不确定为什么会这样。

<form>
<fieldset>
<legend>Create Account:</legend>
Username: <input type="text"><br>
<p>Password:</p>
<input name="password" required="required" type="password" id="password" />
<p>Confirm Password:</p>
<input name="password_confirm" required="required" type="password" 
id="password_confirm" oninput="check(this)" />
<script language='javascript' type='text/javascript'>
function check(input) {
    if (input.value != document.getElementById('password').value) {
        input.setCustomValidity('Password Must be Matching.');
    } else {
        // input is valid -- reset the error message
        input.setCustomValidity('');
    }
}
</script>
<br /><br />
<form action="/path/to/results.html" method="get">
<input type="submit" value="Submit" 
     name="Submit" id="frm1_submit" />
</form>
</fieldset>
</form>

最佳答案

这是因为浏览器对表单提交事件的默认操作是重新加载页面。

您需要调用event.preventDefault()以防止页面刷新。

document
  .querySelector('form')
  .addEventListener('submit', function (event) {
    event.preventDefault()
  })

更新

因此,在进一步挖掘之后,您获得页面刷新而不是预期的表单操作 (<form action="/path/to/results.html" method="get">) 的原因是因为您嵌套了 <form>。元素。第二个表单元素是您定义操作的地方,它会被浏览器忽略。因此,浏览器使用默认操作,即刷新页面。清理您的 HTML(以一种自以为是的方式),它会像您预期的那样工作。

document
  .querySelector('[name="confirm"]')
  .addEventListener('input', check)

function check() {
  var password = document.querySelector('[name="password"]')
  var confirm = document.querySelector('[name="confirm"]')
  if (
    password.value !== confirm.value) {
      confirm.setCustomValidity('Password Must be Matching.');
  } else {
    confirm.setCustomValidity('');
  }
}
input {
  display: block;
  margin-bottom: 15px;
}
<form action="results.html" method="post">
  <fieldset>
    <legend>Create Account:</legend>
    <label>
      Username:
      <input type="text">
    </label>

    <label>
      Password:
      <input type="password" name="password" required>
    </label>

    <label>
      Confirm Password:
      <input type="password" name="confirm" required>
    </label>

    <input type="submit" value="Submit">
  </fieldset>
</form>

注意:这是使用 POST方法,而不是 GET . GET在 URL 中显示输入值,这对密码等敏感信息不利。 POST而是在 HTTP 请求中包含输入值。

干杯

关于javascript - 密码用html验证。获取请求重新加载页面而不是转到提交页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49015974/

相关文章:

javascript - 事后检查后保留所选值

javascript - Angular:如何刷新 html 的一部分( form/div/table )

javascript - 在ES中创建Date对象

javascript - 预加载器淡出,内容淡入

javascript - 传单标记在某些情况下不显示

html - 垂直负边距在 IE8 中不起作用?

javascript - 从输入属性中获取值

javascript - 用 .replaceWith() 替换按钮文本

javascript - 在函数中传递多个回调

html - 如何实现这种布局?