Best way to alphanumeric check in JavaScript

后端 未结 11 2198
逝去的感伤
逝去的感伤 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:48

    Check it with a regex.

    Javascript regexen don't have POSIX character classes, so you have to write character ranges manually:

    if (!input_string.match(/^[0-9a-z]+$/))
      show_error_or_something()
    

    Here ^ means beginning of string and $ means end of string, and [0-9a-z]+ means one or more of character from 0 to 9 OR from a to z.

    More information on Javascript regexen here: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions

    0 讨论(0)
  • 2020-11-28 05:48

    Removed NOT operation in alpha-numeric validation. Moved variables to block level scope. Some comments here and there. Derived from the best Micheal

    function isAlphaNumeric ( str ) {
    
      /* Iterating character by character to get ASCII code for each character */
      for ( let i = 0, len = str.length, code = 0; i < len; ++i ) {
    
        /* Collecting charCode from i index value in a string */
        code = str.charCodeAt( i ); 
    
        /* Validating charCode falls into anyone category */
        if (
            ( code > 47 && code < 58) // numeric (0-9)
            || ( code > 64 && code < 91) // upper alpha (A-Z)
            || ( code > 96 && code < 123 ) // lower alpha (a-z)
        ) {
          continue;
        } 
    
        /* If nothing satisfies then returning false */
        return false
      }
    
      /* After validating all the characters and we returning success message*/
      return true;
    };
    
    console.log(isAlphaNumeric("oye"));
    console.log(isAlphaNumeric("oye123"));
    console.log(isAlphaNumeric("oye%123"));

    0 讨论(0)
  • 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;
    }

    0 讨论(0)
  • 2020-11-28 05:50
        // On keypress event call the following method
        function AlphaNumCheck(e) {
            var charCode = (e.which) ? e.which : e.keyCode;
            if (charCode == 8) return true;
    
            var keynum;
            var keychar;
            var charcheck = /[a-zA-Z0-9]/;
            if (window.event) // IE
            {
                keynum = e.keyCode;
            }
            else {
                if (e.which) // Netscape/Firefox/Opera
                {
                    keynum = e.which;
                }
                else return true;
            }
    
            keychar = String.fromCharCode(keynum);
            return charcheck.test(keychar);
        }
    

    Further, this article also helps to understand JavaScript alphanumeric validation.

    0 讨论(0)
  • 2020-11-28 05:53

    The asker's original inclination to use str.charCodeAt(i) appears to be faster than the regular expression alternative. In my test on jsPerf the RegExp option performs 66% slower in Chrome 36 (and slightly slower in Firefox 31).

    Here's a cleaned-up version of the original validation code that receives a string and returns true or false:

    function isAlphaNumeric(str) {
      var code, i, len;
    
      for (i = 0, len = str.length; i < len; i++) {
        code = str.charCodeAt(i);
        if (!(code > 47 && code < 58) && // numeric (0-9)
            !(code > 64 && code < 91) && // upper alpha (A-Z)
            !(code > 96 && code < 123)) { // lower alpha (a-z)
          return false;
        }
      }
      return true;
    };
    

    Of course, there may be other considerations, such as readability. A one-line regular expression is definitely prettier to look at. But if you're strictly concerned with speed, you may want to consider this alternative.

    0 讨论(0)
提交回复
热议问题