3

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';
geef
  • 589
  • 1
  • 6
  • 8

2 Answers2

15
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.

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
0

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

Reporter
  • 3,897
  • 5
  • 33
  • 47