To check if a string is alphanumeric in javascript
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
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.
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