使用if语句检查用户名中字母和数字的组合

Using if statements to check for combination of letters and numbers in username

本文关键字:数字 组合 语句 if 检查 用户 使用      更新时间:2023-09-26

昨天声明的Javascript。我正在使用JavaScript编写客户端表单验证,并在代码中使用了一堆if语句。

就是这样。:

function validateloginform() { //login page validation test //
    var username = document.forms["form"]["username"].value;
    var password = document.forms["form"]["password"].value;
    var verifypassword = document.forms["form"]["verifypassword"].value;
    if (document.form.username.value == null || document.form.username.value == "") {
        alert("Username is blank...it must be entered");
        document.form.username.focus();
        return false;
    }
    if (document.form.username.value.length != 8) {
        alert("Username must be 8 characters long");
        document.form.username.focus();
        return false;
    } else {
        alert("Correct");
        return true;
    }
}

我如何才能更具体地使用我的语句来包括数字和字母([a-z]或[0-9])字符的组合。

如果用户名或密码不包含字母和数字的组合,则返回false。还有,有没有办法包括特殊字符?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

查看该链接,了解Javascript的正则表达式教程。如果你想切入正题,这里有一个例子(来自教程,但我添加了一些解释)。

<!DOCTYPE html>
<html>  
  <head>  
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
    <meta http-equiv="Content-Script-Type" content="text/javascript">  
    <script type="text/javascript">  
      // Create a regular expression
      // This regular expression is used to check the user's input phone number is in
      // a common phone number format.
      var re = /(?:'d{3}|'('d{3}'))([-'/'.])'d{3}'1'd{4}/;  
      function testInfo(phoneInput){  
        // The exec() call below checks if the phoneInput.value matches the regex re
        // which was defined above.
        var OK = re.exec(phoneInput.value);  
        // OK will be true or false depending on if phoneInput.value matched the regex.
        if (!OK)  
          window.alert(RegExp.input + " isn't a phone number with area code!");  
        else
          window.alert("Thanks, your phone number is " + OK[0]);  
      }  
    </script>  
  </head>  
  <body>  
    <p>Enter your phone number (with area code) and then click "Check".
        <br>The expected format is like ###-###-####.</p>
    <form action="#">  
      <input id="phone"><button onclick="testInfo(document.getElementById('phone'));">Check</button>
    </form>  
  </body>