Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a username is taken, by checking against a JavaScript array.

var y=document.forms["form"]["user"].value
    if (y==null || y=="" )
        {
            alert("Username cannot be Blank");
            return false;
        };

var x = new Array();
    x[0] = "bill";  
    x[1] = "ted";   
    x[2] = "jim";   
    for ( keyVar in x ) 
        {
            if (x==y)
            {
                alert("Username Taken");
                return false;
            };

        };

How do I compare a variable to that in a JavaScript array, I managed to make the example above, but the second part, the bit I need, doesn't work. any ideas ?

like image 334
Rudiger Kidd Avatar asked Dec 27 '22 10:12

Rudiger Kidd


2 Answers

You can simply check an array with the Array.prototype.indexOf method.

var x = [ 'bill', 'ted', 'jim' ],
    y = 'ted';

if( x.indexOf( y ) > -1 ) {
    alert('Username Taken');
    return false;
}
like image 144
jAndy Avatar answered May 16 '23 17:05

jAndy


You should use an object instead:

var y = document.forms["form"]["user"].value;
if (y == null || y == "") {
    alert("Username cannot be Blank");
    return false;
};

var x = {};
x["bill"] = true;
x["ted"] = true;
x["jim"] = true;
if (x[y] === true) {
    alert("Username Taken");
    return false;
}
like image 34
Nicola Peluchetti Avatar answered May 16 '23 16:05

Nicola Peluchetti