timpone
timpone

Reputation: 19969

Regular expression for checking if string is a-zA-Z0-9

I am trying to check if a string is all a-zA-Z0-9 but this is not working. Any idea why?

var pattern=/^[a-zA-Z0-9]*$/;
var myString='125 jXw';  // this shouldn't be accepted
var matches=pattern.exec(myString);
var matchStatus=1;  // say matchStatus is true

if(typeof matches === 'undefined'){
  alert('within here');
  matchStatus=0; // matchStatus is false
};

if(matchStatus===1){
  alert("there was a match");
}

Upvotes: 2

Views: 19284

Answers (5)

Krucamper
Krucamper

Reputation: 371

function KeyString(elm)
{
    var pattern = /^[a-zA-Z0-9]*$/;

    if( !elm.value.match(pattern))
    {
        alert("require a-z and 0-9");
        elm.value='';
    }
}

Upvotes: 1

benqus
benqus

Reputation: 1149

I would test it only - in this case:

var pattern = /^[a-z0-9]+$/i;
var myString = '125 jXw';
var matchStatus = 1;  // say matchStatus is true

if (!pattern.test(matches)) {
    matchStatus = 0; // matchStatus is false
};

if(matchStatus === 1){
    alert("there was a match");
}

Upvotes: 0

Ben McCormick
Ben McCormick

Reputation: 25728

Try

if(matches === null){
  alert('within here');
  matchStatus=0; // matchStatus is false
};

if(matchStatus===1){
  alert("there was a match");
}

Regex.exec returns null if there's no match, not undefined. So you need to test that.

It seems to work as you expect like that: fiddle

Documentation for exec: MDN

Upvotes: 1

SelftaughtMonk
SelftaughtMonk

Reputation: 1037

If im not wrong, your regex has no provision for SPACE and your string has space in it. If you want to allow space try this way /^[a-zA-z0-9\ ]*$/

Upvotes: 1

Bergi
Bergi

Reputation: 664548

exec() returns null if no match is found, which is typeof object not undefined.

You should use this:

var matches = pattern.exec(myString); // either an array or null
var matchStatus = Boolean(matches);

if (matchStatus)
    alert("there was a match");
else
    alert('within here');

Or just use the test method:

var matchStatus = pattern.test(myString); // a boolean

Upvotes: 7

Related Questions