I'm quite new to JS and am trying to check if a user or any value exists in a JavaScript object in real time, the goal is to implement this in Firebase in order to prevent user registration if that username has already been taken but I am doing it locally first because Im learning. This is what I have so far.
let input = document.getElementById('input')
let btn = document.getElementById('btn')
btn.disabled = false
let users = [
{
uname: "mark"
},
{
uname: "sarah"
},
{
...others uname
}
]
input.addEventListener('input', () => {
input.value = input.value.replace(regex, "")
check(input.value)
})
function check(val) {
users.forEach((item) => {
let uname = item.uname
if (uname.indexOf(val) > -1 && uname === val) {
console.log('That user name has been taken')
btn.disabled = true
} else {
console.log('Ok')
btn.disabled = false
}
})
}
The problem with that is when I typed in the input element Im getting both the if and else triggered and while (val) matches some key/value pairs the others won't and then I am able to use whatever username Im typing which is not what I want.
How can I solved this? Thanks.
You aren't checking to see if the username has been found.
function isUsernameAvailable (val) {
for (var i = 0; i < users.length; i++) {
var uname = users[i].name;
if (uname === val) {
console.log('That user name has been taken')
btn.disabled = true
return false; // the username is taken, we can stop checking
}
}
console.log('Ok')
btn.disabled = false
return true;
}
Also, forEach
doesn't let you exit the loop early and you don't need to check every user after you found a match (if you find a match).