简体   繁体   English

验证密码字段和确认密码字段

[英]Validation of the password field and the confirm password field

Good night.晚安。 I'm developing a project for study and I really wanted to do the validation of the password field and the validation of the confirmSenha field, The idea is that when the user enters a different password.我正在开发一个研究项目,我真的很想做密码字段的验证和 confirmSenha 字段的验证,这个想法是当用户输入不同的密码时。 a message is returned saying that the passwords do not match.返回一条消息说密码不匹配。 Below is the scope of my code.下面是我的代码的 scope。

function validarPasswordConfirm(password, confirmPassword) {

  var typedpassword = document.getElementsByName('password').value;
  var confirmTypedPassword = document.getElementsByName('passwordConfirm').value;

  if(typedpassword !== confirmTypedPassword) {
    return { value: false, text: 'Passwords are not the same.' }
  } else {
    return { value: true, text: '' }
  }
}

I'm trying to validate the password field with the confirmpassword field我正在尝试使用 confirmpassword 字段验证密码字段

The function getElementsByName returns an array, so you can't access the value property like that. function getElementsByName 返回一个数组,因此您不能像那样访问 value 属性。

I recommend use getElementById instead.我建议改用 getElementById。

I noticed a few problems with your code.我注意到您的代码存在一些问题。


Firstly, var is not used anymore ( see why ).首先,不再使用var查看原因)。 You should use an alternative.您应该使用替代方法。

Alternatives for var are below. var的替代品如下。

  1. let - Use this for variables that can be changed. let - 将它用于可以更改的变量。
  2. const - Use this for variables that cannot be changed (constant). const - 将其用于无法更改的变量(常量)。

Secondly, getElementsByName() returns aNodeList , which is an iterable (like an array ).其次, getElementsByName()返回一个NodeList ,它是一个可迭代的(类似于array )。 This means that .value is undefined in a NodeList .这意味着.valueNodeListundefined

To fix it, change your code to below.要修复它,请将您的代码更改为以下内容。

const typedPassword = document.querySelector("#password").value;
const confirmTypedPassword = document.querySelector("#passwordConfirm").value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM