如何检查用户名是否以字母开头? JAVASCRIPT - 没有正则表达式

时间:2015-11-06 16:32:14

标签: javascript

如何检查输入的用户名是否以字母而不是使用正则表达式开头?我想使用isLetter函数,那么我该如何去做呢?

<html>
   <head></head>
   <body>
      <script type = "text/javascript">
         var BR = "<br />";
         var username = "";
         var letter1 = ""
         letter1 = username.substr(0,1);
         accepted = 0;
         document.write("Enter a username that has the following:" + BR);
         document.write("The username must have at least 8 characters." + BR);
         document.write("The username must must begin with a letter." + BR);
         document.write("The username must must have one digit." + BR);
         try {
             username = prompt("Please enter a username that follows these rules:");
             if (username.length >= 8) {
                 throw("This length is in range");
             }
             else {
                 throw("This length is not in range"); 
             }
         } 
         catch (x) {
             if (x == "This length is in range") {
                 document.write("This length is in range");
                 accepted = 0;
             }
             else if (x =="This length is not in range") {
                 document.write("The length is not in range.");
                 accepted = 1;
             }
         }
      </script>
   </body>
</html>

2 个答案:

答案 0 :(得分:0)

试试这个:

if(isNaN(str[0])){
  alert('true');
}

将str [0]替换为用户名[0]或类似的东西

答案 1 :(得分:0)

function isLetter (str) {
    var c = str.charCodeAt(0);
    if ( ((c >= 65) && (c <= 90)) || ((c >= 97) && (c <= 122)) ) {
        alert("It's a letter!!!");
    }
    else {
        alert("It's not a letter!!!");
    }
}