首页 > 解决方案 > 关于验证确认密码和纯字母文本是否正确

问题描述

这对于验证确认密码和纯字母文本是否正确。它不工作请帮助。谢谢!

function validation(password, confirmpassword) {
    var password = document.form.password.value;
    var confirmpassword = document.form.confirmpassword.value;

    if (password.length <= 6) {
        alert("password must be more thank 6 characters long");
        return false;
    }
    if (password.value !== confirmpassword.value)
        alert("password should match");
    return false;
}

function allLetter(inputtxt) {
    var letters = /^[a-z]*$/i;
    if (!inputtxt.value.match(letters)) {
        alert("Please input letters only");
    }
}

标签: javascript

解决方案


Here's how you can do it:

function validation(event) {
  event.preventDefault();
  var password = document.querySelector(".password").value;
  var confirmpassword = document.querySelector(".confirm-password").value;

  if (password.length <= 6) {
    alert("password must be more thank 6 characters long");
    return false;
  }

  if (password !== confirmpassword) {
    alert("password should match");
    return false;
  }
  alert("password valid");
  return true;
}

function allLetter(inputtxt) {
  var letters = /^[a-z]*$/i;
  if (!letters.test(inputtxt)) {
    alert("Please input letters only");
  }
}

const passwordInputs = document.querySelectorAll("input[type=password]");
const validator = document.querySelector(".validate");

passwordInputs.forEach(function(passwordInput) {
  passwordInput.addEventListener("input", function(e) {
    allLetter(e.target.value);
  });
});

validator.addEventListener("click", function(event) {

  console.log("can proceed", validation(event));
});
<form>
  <input class="password" type="password"></input>
  <input class="confirm-password" type="password"></input>


  <button class="validate">Validate</button>
</form>


推荐阅读