Best way to alphanumeric check in JavaScript

后端 未结 11 2239
逝去的感伤
逝去的感伤 2020-11-28 05:09

What is the best way to perform an alphanumeric check on an INPUT field in JSP? I have attached my current code



        
11条回答
  •  庸人自扰
    2020-11-28 05:49

    If you want a simplest one-liner solution, then go for the accepted answer that uses regex.

    However, if you want a faster solution then here's a function you can have.

    console.log(isAlphaNumeric('a')); // true
    console.log(isAlphaNumericString('HelloWorld96')); // true
    console.log(isAlphaNumericString('Hello World!')); // false
    
    /**
     * Function to check if a character is alpha-numeric.
     *
     * @param {string} c
     * @return {boolean}
     */
    function isAlphaNumeric(c) {
      const CHAR_CODE_A = 65;
      const CHAR_CODE_Z = 90;
      const CHAR_CODE_AS = 97;
      const CHAR_CODE_ZS = 122;
      const CHAR_CODE_0 = 48;
      const CHAR_CODE_9 = 57;
    
      let code = c.charCodeAt(0);
    
      if (
        (code >= CHAR_CODE_A && code <= CHAR_CODE_Z) ||
        (code >= CHAR_CODE_AS && code <= CHAR_CODE_ZS) ||
        (code >= CHAR_CODE_0 && code <= CHAR_CODE_9)
      ) {
        return true;
      }
    
      return false;
    }
    
    /**
     * Function to check if a string is fully alpha-numeric.
     *
     * @param {string} s
     * @returns {boolean}
     */
    function isAlphaNumericString(s) {
      for (let i = 0; i < s.length; i++) {
        if (!isAlphaNumeric(s[i])) {
          return false;
        }
      }
    
      return true;
    }

提交回复
热议问题