geef
geef

Reputation: 589

Javascript Function Valid Username

What's the best way/right way to create a javascript function that checks to see that the user has adhered to the valid character list below (user would enter a username through a html form) - if character list is adhered to function would return true - otherwise false.

validcharacters = '1234567890-_.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

Upvotes: 3

Views: 8435

Answers (2)

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99879

function usernameIsValid(username) {
    return /^[0-9a-zA-Z_.-]+$/.test(username);
}

This function returns true if the regex matches. The regex matches if the username is composed only of number, letter and _, ., - characters.

You could also do it without regex:

function usernameIsValid(username) {
    var validcharacters = '1234567890-_.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

    for (var i = 0, l = username.length; i < l; ++i) {
        if (validcharacters.indexOf(username.substr(i, 1)) == -1) {
            return false;
        }
        return true;
    }
}

For this one, we iterate over all characters in username and verify that the character is in validcharacters.

Upvotes: 15

Reporter
Reporter

Reputation: 3948

one way is to read each character from the input field and use the indexOf() function

Upvotes: 0

Related Questions