Best way to alphanumeric check in JavaScript

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

    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"));

提交回复
热议问题