Как я могу проверить соответствие паролей формы с помощью JavaScript? - PullRequest
0 голосов
/ 29 сентября 2019

У меня есть базовая HTML-форма с паролем и полями для подтверждения пароля.Я хочу разрешить пользователям продолжать работу только в случае совпадения паролей.Если пароли не совпадают, я хочу, чтобы пользователь получил уведомление.

Я думаю, что то, что у меня сейчас есть, близко, но JS по-прежнему ничего не делает.

HTML

<form class="ajax-form" id="pwreset" method="post" onsubmit="return verifyPassword()" action="/set-password">
        <div id="userinput">
      <label for="username">Username</label>
            <input type="text" id="username" name="username"/><br/>
            <label for="new_password">Password</label>
            <input type="Password" id="new_password" name="new_password"/><br/>
            <label for="verifyPassword">Verify Password</label>
            <input type="password" id="verifyPassword" name="verifyPassword"/><br/>
            <input type="hidden" id="uuid" name="uuid" value="{{uuid}}"/>
      <p><input class="button" type="submit" value="SUBMIT"></p>
        </div>
</form>

JS

function verifyPassword() {
  let pass1 = document.getElementById("new_password").value;
  let pass2 = document.getElementById("verifyPassword").value;
    let match = true;
  if (pass1 != pass2) {
    //alert("Passwords Do not match");
    document.getElementById("new_password").style.borderColor = "#ff0000";
    document.getElementById("verifyPassword").style.borderColor = "#ff0000";
    match = false;
  }
  else {
    alert("Passwords match.");
  }
  return match;
}

Ответы [ 2 ]

0 голосов
/ 29 сентября 2019

Вот пример.Я создал конструктор passwordGroup для централизации информации.Так проще писать тесты.

var form = document.forms[0];
var pass1 = form.querySelector('[data-password]');
var pass2 = form.querySelector('[data-password-confirmation]');
var submitButton = form.querySelector('button[type="submit"]');

// PasswordGroup constructor
var PasswordGroup = function () {
  this.password = '';
  this.passwordConfirmation = '';
};

// method to update the passwords values
PasswordGroup.prototype.setValues = function(data) {
  this.password = data.password;
  this.passwordConfirmation = data.passwordConfirmation;
};

// method to check the password's equality
PasswordGroup.prototype.match = function() {
  return !!(this.password 
  && this.passwordConfirmation 
  && this.password === this.passwordConfirmation);
};

/*
* Enable/disable the submit button if passwords do not match
*/
function validateSubmit() {
  if(passwordGroup.match()) {
    submitButton.removeAttribute('disabled');
  } else {
    submitButton.setAttribute('disabled', 'disabled');
  }
}

// passwordGroup instance
var passwordGroup = new PasswordGroup();

// objecto to store the current values
var passwordsValues = {
  password: '',
  passwordConfirmation: '',
};

// event triggered after enter a new value in the password's field
var onPasswordChange = function(e) {
  var target = e.target;
  var targetValue = target.value;
  
  if(target.dataset.hasOwnProperty('password')) {
    passwordsValues.password = targetValue;
  } else if (target.dataset.hasOwnProperty('passwordConfirmation')) {
    passwordsValues.passwordConfirmation = targetValue;
  }

  passwordGroup.setValues(passwordsValues);
  validateSubmit();
};

// event attribution
pass1.onkeyup = onPasswordChange;
pass2.onkeyup = onPasswordChange;
input {
  display: block;
}
<form action="" name='account'>
  <input type="text" placeholder="name" /> 
  <input type="password" data-password placeholder="password"/>
  <input type="password" data-password-confirmation placeholder="repeat password"/>
  <button type="submit" disabled="disabled">Enviar</button>
</form>

<p data-message></p>
0 голосов
/ 29 сентября 2019

Есть некоторые проблемы, которые могут возникнуть из-за вызова javascript в HTML.

В вашем случае, функция, вероятно, была определена после HTML, поэтому элемент не имел к ней доступа.

Вы можете использовать это вместо:

function verifyPassword() {
  let pass1 = document.getElementById("new_password").value;
  let pass2 = document.getElementById("verifyPassword").value;
  let match = true;
  if (pass1 != pass2) {
    //alert("Passwords Do not match");
    document.getElementById("new_password").style.borderColor = "#ff0000";
    document.getElementById("verifyPassword").style.borderColor = "#ff0000";
    match = false;
  }
  else {
    alert("Passwords match.");
  }
  return match;
}

document.getElementById('pwreset').onsubmit = verifyPassword;
<form class="ajax-form" id="pwreset" method="post" action="/set-password">
  <div id="userinput">
    <label for="username">Username</label>
    <input type="text" id="username" name="username" /><br/>
    <label for="new_password">Password</label>
    <input type="Password" id="new_password" name="new_password" /><br/>
    <label for="verifyPassword">Verify Password</label>
    <input type="password" id="verifyPassword" name="verifyPassword" /><br/>
    <input type="hidden" id="uuid" name="uuid" value="{{uuid}}" />
    <p><input class="button" type="submit" value="SUBMIT"></p>
  </div>
</form>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...