Best way to alphanumeric check in Javascript

Can you please suggest the best possible way to perform an alpha numeric check on an INPUT field in JSP? I have attached my current code and I know its no where close to perfect :)

<script type="text/javascript">
  function validateCode(){
      var TCode = document.getElementById('TCode').value;
      for(var i=0; i<TCode.length; i++)
      {
        var char1 = TCode.charAt(i);
        var cc = char1.charCodeAt(0);

        if((cc>47 && cc<58) || (cc>64 && cc<91) || (cc>96 && cc<123))
        {

        }
         else {
         alert('Input is not alphanumeric');
         return false;
         }
      }
     return true;     
   }

Answers:

Answer

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.

Answer

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

Answer

I would create a String prototype method:

String.prototype.isAlphaNumeric = function() {
  var regExp = /^[A-Za-z0-9]+$/;
  return (this.match(regExp));
};

Then, the usage would be:

var TCode = document.getElementById('TCode').value;
return TCode.isAlphaNumeric()
Answer
    // 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.

Answer

Excuse me all, no controversy. But for the community to grow as it has grown me in these years, it is good to make some notes.

The real alphanumeric string is like "0a0a0a0b0c0d" and not like "000000" or "qwertyuio".

All the answers I read here, returned true in both cases. And forgive me, IMHO, this is not right.

If I want to check if my "00000" string is alphanum, my "human" answer is unquestionably FALSE.

Why? Simple. I cannot find any letter char. So, is a simple numeric string [0-9].

On the other hand, if I wanted to check my "abcdefg" string, my "human" answer is even FALSE. I don't see numbers, so it's not alphanumeric. Just alpha [a-zA-Z].

The Michael Martin-Smucker's answer has been illuminating.

However he was aimed at achieving better performance instead of regex. This is true, using a low level way there's a better perfomance. But results it's the same. The strings "0123456789" (only numeric), "qwertyuiop" (only alpha) and "0a1b2c3d4f4g" (alphanumeric) returns TRUE as alphanumeric. Same regex /^[a-z0-9]+$/i way. The reason why the regex does not work is as simple as obvious. The syntax [] indicates or, not and. So, if is it only numeric or if is it only letters, regex returns true.

But, the Michael Martin-Smucker's answer was nevertheless illuminating. For me. It allowed me to think at "low level", to create a real function that unambiguous processes an alphanumeric string. I called it like PHP relative function ctype_alnum (edit 2020-02-18: Where, however, this checks OR and not AND).

Here's the code:

function ctype_alnum(str) {
  var code, i, len;
    var isNumeric = false, isAlpha = false; //I assume that it is all non-alphanumeric



  for (i = 0, len = str.length; i < len; i++) {
    code = str.charCodeAt(i);


        switch (true){
            case code > 47 && code < 58: // check if 0-9
                isNumeric = true;
                break;
            case (code > 64 && code < 91) || (code > 96 && code < 123): //check if A-Z or a-z
                isAlpha = true;
                break;
            default: // not 0-9, not A-Z or a-z
                return false; //stop function with false result, no more checks

        }

  }

  return isNumeric && isAlpha; //return the loop results, if both are true, the string is certainly alphanumeric
};

... and here's the DEMO

I came to this discussion because I was looking for an alternative in javascript to the PHP function. I didn't find the answer "ready-to-go", but as often happens on Stackoverflow, the concept of knowledge and comparison with each other is something sublime, that leads you to think about someone's answer and find together the solution you were looking for, but you didn't think you knew it.

And share it!

Best

Oscar

Answer

To check whether input_string is alphanumeric, simply use:

input_string.match(/[^\w]|_/) == null
Answer

In a tight loop, it's probably better to avoid regex and hardcode your characters:

function isAlphanumeric(char) {
    return "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(char) > -1;
}
Answer

You can use this regex /^[a-z0-9]+$/i

Answer

You don't need to do it one at a time. Just do a test for any that are not alpha-numeric. If one is found, the validation fails.

function validateCode(){
    var TCode = document.getElementById('TCode').value;
    if( /[^a-zA-Z0-9]/.test( TCode ) ) {
       alert('Input is not alphanumeric');
       return false;
    }
    return true;     
 }

If there's at least one match of a non alpha numeric, it will return false.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.