简体   繁体   中英

javascript - check first char of username

English isn't my primary language,so I'll try to do my best to explain myself...I need to, using javascript, check the first letter of input username of the user,and see if it's between AZ or az . If not it will delete the string the the user entered. Why isn't the code working?

function UsernameRegisterVaildation()
{
    var username = document.getElementById("usernameRegister");
    var x = false;
    var y = false;
    if (x.CharAt(0) >= 'A' && x.CharAt(0) <= 'Z')
        x = true;

    if (y.CharAt(0) >= 'a' && y.CharAt(0) <= 'z')
        y = true;

    if (!x || !y)
    {
        alert("WRONG USERNAME");
    }
}

and here's the input:

        Username: <input type="text" id="usernameRegister" name="UserNameRegister" onchange="UsernameRegisterVaildation();"/>

It's charAt , not CharAt . Also, you've got a reference to the element that holds the username, not the username itself - get the value property.

You may as well just use one regular expression, though:

if(!/^[a-z]/i.test(username.value)) {
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM