user11112512
user11112512

Reputation:

Checking if fields are empty in Javascript?

I am trying to check if specific fields are empty or not so I can Authenticate users using Firebase. However JavaScript seems to be skipping over multiple bits of code and constantly only showing the same message onscreen. Here is my code...

let user = document.getElementsByName('username');
let em2 = document.getElementsByName('mail2');
let rem = document.getElementsByName('repeatMail');
let pass2 = document.getElementsByName('password2');
let rpass = document.getElementsByName('repeatPassword');

if ((user === '') && (em2 === '')) {
    alert('Please make sure all fields are filled in correctly. Thank you');
} else if ((rem === '') && (pass2 === '')) {
    alert('Please make sure all fields are filled in correctly. Thank you');
} else if (rpass === '') {
    alert('Please make sure all fields are filled in correctly. Thank you');
} else if ((em2 !== rem) && (pass2 !== rpass)) {
    alert('Please make sure all repeat fields match their parents. Thank you');
} else {
    checkUsername()
}

It will constantly just skip to the last else if statement and no matter what will always give me the error I setup even if the fields do match in HTML. I am probably just overlooking something but I have been struggling with this for a while now. Does anyone know a solution? By the way this code is inside a function but that but I've given that a unique name and all it is, is a simple...

function regSecurity() {

}

Upvotes: 0

Views: 245

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386786

Beside the neede value property of the input elements, you need to check for emptyness and then to check if both wanted inputs are the same.

function checkUsername() {
    console.log('checkUsername');
    return false;
}

function check() {
    let user = document.getElementById('username').value,
        em2 = document.getElementById('mail2').value,
        rem = document.getElementById('repeatMail').value,
        pass2 = document.getElementById('password2').value,
        rpass = document.getElementById('repeatPassword').value;

    if (!user || !em2 || !rem || !pass2 || !rpass) {
        alert('Please make sure all fields are filled in correctly. Thank you');
        return false;
    }
    if (em2 !== rem || pass2 !== rpass) {
        alert('Please make sure all repeat fields match their parents. Thank you');
        return false;
    }
    return checkUsername();
}
<form onsubmit="return check()">
<input type="text" id="username" placeholder="username">
<input type="text" id="mail2" placeholder="mail2">
<input type="text" id="repeatMail" placeholder="repeatMail">
<input type="text" id="password2" placeholder="password2">
<input type="text" id="repeatPassword" placeholder="repeatPassword">
<input type="submit">
</form>

Upvotes: 1

Related Questions