'To check if a string is alphanumeric in javascript

I want to check if a string is STRICTLY ALPHANUMERIC in javascript. i have tried this:

var Exp = /^[0-9a-z]+$/;
if(!pwd.match(Exp))
alert("ERROR")

But the problem with this is it passes input sting if it contains all alphabet or all numeric, i want the function to pass if it contains both Characters and Numbers.



Solution 1:[1]

Try this regex:

/((^[0-9]+[a-z]+)|(^[a-z]+[0-9]+))+[0-9a-z]+$/i

Which allows only Alphanumeric.

It doesn't allow:

  • Only Alpha
  • Only Numbers

Refer LIVE DEMO

Updated:

Below regex allows:

/^([0-9]|[a-z])+([0-9a-z]+)$/i
  • AlphaNumeric
  • Only Alpha
  • Only Numbers

Solution 2:[2]

Felix Kling's answer is the best single-regex solution in my opinion, but I would consider doing it with three patterns. This allows you to return useful error messages:

if(pwd.match(/[^0-9a-z]/i))
    alert("Only letters and digits allowed!");
else if(!pwd.match(/\d/))
    alert("At least one digit required!");
else if(!pwd.match(/[a-z]/i))
    alert("At least one letter required!");
else
    // process pwd

You should consider allowing non-alphanumeric characters for your passwords though - that would make them a lot safer.

Solution 3:[3]

You can use lookaheads:

/^(?=.*?[a-z])(?=.*?\d)[a-z\d]+$/i
   ^^^^^^^^^^  ^^^^^^^
    at least   at least
   one letter  one digit

FYI, restricting the allowed characters for a password reduce the entropy a lot (there are only 36 different characters now) and hence makes them much easier to crack. Don't do this restriction. Checking whether the string contains a certain type of character is fine though (well, there are some theories that this reduces entropy as well, but I don't have enough knowledge about that).

See also: Regex to accept atleast one alphabet one numeric char and one special Character

Solution 4:[4]

var pwd = 'somevalue';
if(pwd.match("^[a-zA-Z0-9]*$")){
   alert('aplanumeric');
}
else{
   alert('Not alphanumeric');
}

Solution 5:[5]

The right function is

function isAlphaNumeric(str) {
  return str.match(/^[a-z0-9]+$/i) !== null;
}

Solution 6:[6]

I hate to be that guy, but I also hate all the answers I found here, so here's mine.

function isalnum(data) {
  return !/\W|_/.exec(data)
}

What's going on here?

  • \w is the "word" class.

    • it's a shortcut to match alphanumerics and the underscore (_)
    • it's meant to be used to match identifiers in formal languages
    • You could write it [A-za-z0-9_]
  • \W it's the "negated" form of the "word" class.

    • It's the opposite of "\w".
    • You could also write it [^A-za-z0-9_]

If you didn't bother about accepting an underscore and were simply sanitizing some inputs, you could just have used:

!/\W/.exec(data)

or even, the more straighforward:

/^\w*$/.exec(data)

And here I'm using RegExp.exec() but you could as well prefer using String.match() and in that case you would write

!data.match(/\W|_/)

And why, YES, I do like regexps.

Solution 7:[7]

String myString1 = "abcdefghijklmnop1";

    /**
     * To Check Alphanumeric myString1==ABCD is Working;myString1==123 is Working;myString1==ABCD123 is not Working
     */
    Pattern p1 = Pattern.compile("^[a-zA-Z0-9]*$");

The p1 will show false if you check whether it contains bothe alphabet and numeric so use Pattern p if you want to check whether it either contains alphabet or numeric you can use Pattern p1

    /**
     * To Check both Alpha and Numeric only myString1==ABCD123 is Working
     */

    Pattern p = Pattern
            .compile("[a-zA-Z]+[0-9]+[a-zA-Z0-9]*|[0-9]+[a-zA-Z][a-zA-Z0-9]*");

    boolean hasSpecialChar = p.matcher(myString1).find();

    if (hasSpecialChar) {

        System.out.println("Working");

    } else {

        System.out.println("not Working");

    }

                     /***************OR*******************/

char[] charArray = myString1.toCharArray();

    for (char ch : charArray) {

        if (Character.isUpperCase(ch)) {

        }
        if (Character.isLetter(ch)) {

            containsletter = true;
        }

        if (Character.isDigit(ch)) {

            containsdigits = true;

        }
     }
       if(containsletter&&containsdigits){

            System.out.println("Working");

       }
       else{

            System.out.println("not Working");

       }

}

Solution 8:[8]

A really simple way to do this without regexes:

function stringIsStrictlyAlphaNumeric(string)
{
    //returns true for letters, digits or both
    var stringIsLooselyAlphanumeric = string => [...string].every(character => '0123456789abcdefghijklmnopqrstuvwxyzABCEDEFGHIJKLMNOPQRSTUVWXYZ'.includes(character));
    //returns true for digits only 
    var stringIsComposedOfDigitsOnly = string => [...string].every(character => '0123456789'.includes(character));  
    //returns true for letters only 
    var stringIsComposedOfLettersOnly = string => [...string].every(character => 'abcdefghijklmnopqrstuvwxyzABCEDEFGHIJKLMNOPQRSTUVWXYZ'.includes(character)); 
    //returns true for letters and digits only.
    return stringIsLooselyAlphanumeric(string) && !stringIsComposedOfDigitsOnly(string) && !stringIsComposedOfLettersOnly(string);  
}

Please use like so:

stringIsStrictlyAlphaNumeric('hello123'); //returns true
stringIsStrictlyAlphaNumeric('hello');    //returns false
stringIsStrictlyAlphaNumeric('123');      //returns false
stringIsStrictlyAlphaNumeric('');         //returns false

Solution 9:[9]

This will work for any number of characters (as opposed to accepted answer)

/^[a-z0-9]*$/i

Solution 10:[10]

Regex:

/^[a-z0-9]+$/i

Faster than regex:

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;
};

Source: https://www.py4u.net/discuss/280185

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Martin Ender
Solution 3 Community
Solution 4 Deepu
Solution 5 user108828
Solution 6
Solution 7
Solution 8 100PercentVirus
Solution 9 coreycosman
Solution 10 Geoffrey Hale