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, a message is returned saying that the passwords do not match. Below is the scope of my code.
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
The function getElementsByName returns an array, so you can't access the value property like that.
I recommend use getElementById instead.
I noticed a few problems with your code.
Firstly, var is not used anymore (see why). You should use an alternative.
Alternatives for var are below.
let - Use this for variables that can be changed.const - Use this for variables that cannot be changed (constant).Secondly, getElementsByName() returns a NodeList, which is an iterable (like an array). This means that .value is undefined in a NodeList.
To fix it, change your code to below.
const typedPassword = document.querySelector("#password").value;
const confirmTypedPassword = document.querySelector("#passwordConfirm").value;