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';
1
  • Don't use loops and nested loops because it's not efficient. You have to use regular expressions. Commented Sep 7, 2011 at 9:09

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

could you explain use of !!, isn't it same with username.match(/^[0-9a-zA-Z_.-]+$/)?
The converts .match's return value to a boolean. See stackoverflow.com/questions/784929/…
Or do /^[0-9a-zA-Z_.\-]+$/.test(username). This may be a cheaper operation than match.
Can not remove the first char when backspace to revise?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.