开发者

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 c开发者_开发问答haracter list is adhered to function would return true - otherwise false.

validcharacters = '1234567890-_.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜