0

How can I find out if a text input is a certain text?

I tried this

<script>
    var b = document.getElementById('button')
    var u = document.getElementById('username')
    var p = document.getElementById('password')
    
    var bannedUsers = ["user1012"];
    
    b.onclick = function() {
      if(u.value.length <= 20 && p.value.length >= 6 && u.value.length >= 3 && !u.value === bannedUsers) {
        location.href = "";
    };
      
      if(u.value.length > 20) {
        return alert('Username needs to be below 20 characters.')
      } else if(u.value.length < 3) {
        return alert('Username needs to be above 2 characters')
      }
      
      if(p.value.length < 6) {
        return alert('Password needs to be over 6 characters.')
      }
      
      if(u.value === bannedUsers) {
        return alert('That username is banned.')
      }
    }
    </script>

But it ended up just taking me to the page instead of saying "This username is banned"

Connell.O'Donnell
  • 3,603
  • 11
  • 27
  • 61
  • 1
    do it server-side and make an ajax call, around the same time as you validate the above and check for an existing user with the same username – Lawrence Cherone Mar 02 '21 at 18:57
  • Does this answer your question? [How do I check if an array includes a value in JavaScript?](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-a-value-in-javascript) – Heretic Monkey Mar 02 '21 at 19:03
  • Also, make sure legit words aren't banned! Some words have bad words within them, so please don't block those! – Penguin Mar 02 '21 at 19:16
  • It does not really make sense to be returning an alert call `alert('xxxx'); return false;` It will work, just does not the best thing. – epascarello Mar 02 '21 at 20:08

2 Answers2

2

You need to use the includes method.

bannedUsers.includes(u.value)

what you're doing right now is checking if the string is the array bannedUsers, translating to this: 'user1012' === '[object Object]'

Keimeno
  • 2,512
  • 1
  • 13
  • 34
-1

You can use the Array.prototype.includes method to test if a given value is in an array. includes will return a boolean true or false.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

if (bannedUsers.includes(u.value) {
  return alert('That username is banned.')
}
Benjamin
  • 3,428
  • 1
  • 15
  • 25