Ghoul Fool
Ghoul Fool

Reputation: 6949

Alpha-numeric with whitespace regex

Just when you think you've got a handle on regex; it all comes undone. Hoping to return a false check if anything other than alpha numeric and whitespace characters are found.

function checkName(fname)
{ 
  var rexp = new RegExp(/[^a-zA-Z0-9]\s/gim)
  if (!rexp.test(fname))
    {
      alert ("'" + fname + "'\nis okay")
    }
    else
    {
       alert ("'" + fname + "'\nis NOT okay")
    }
  return !rexp.test(fname)
}

I would hope that the above code would return for the following

Upvotes: 1

Views: 3148

Answers (4)

Scott Sauyet
Scott Sauyet

Reputation: 50787

Although much of the discussion is right, everything seems to be missing the point that you are inverting character classes and then inverting the results in your function. This is logically hard to read. You also do two tests on the regex for no good reason. Much cleaner would be something like this:

function checkName(fname) { 
    var result = /^[a-z0-9\s]+$/i.test(fname)

    if (result) {
        alert ("'" + fname + "'\nis okay")
    } else {
        alert ("'" + fname + "'\nis NOT okay")
    }
    return result;
}

Update: It looks like Jack's edits captured these points too. (Always a minute late and a nickel short...)

Upvotes: 2

Ja͢ck
Ja͢ck

Reputation: 173562

A few things:

  1. /something/ is the short notation for new RegExp('something'); you shouldn't mix them up.

  2. You need to move the \s inside the character class; otherwise you match a character that's not alphanumeric followed by a space.

  3. I don't think you need all those modifiers:

    1. /m is only useful if you have anchors in your expression,
    2. /i can be used if you remove A-Z or a-z from the character class,
    3. /g is only useful for when you need to match multiple times, but in your case the first match is enough.

      var rexp = /[^a-zA-Z0-9\s]/;
      

The whole function can be written like this:

function checkName(fname)
{
    return !/[^a-zA-Z0-9\s]/.test(fname);
}

Instead of using double negatives, it would be better to say "only allow these characters":

function checkName(fname)
{
    return /^[a-zA-Z0-9\s]*$/.test(fname);
}

If you need to test for non-empty names as well, you should use /^[a-zA-Z0-9\s]+$/.

Upvotes: 1

tckmn
tckmn

Reputation: 59273

[^a-zA-Z0-9]\s

Your regex requires the whitespace to be after the letters/numbers.

To fix it, move the \s inside the brackets.

You still have to do one more thing though. The regex will only match one of these characters. Add a + to match one or more.

Therefore, fixed regex:

[^a-zA-Z0-9\s]+

Upvotes: 1

palaѕн
palaѕн

Reputation: 73906

Try:

function checkName(fname)
{ 
  var rexp = new RegExp(/^[a-z0-9\s]+$/i)
  if (!rexp.test(fname))
    {
      alert ("'" + fname + "'\nis okay")
    }
    else
    {
       alert ("'" + fname + "'\nis NOT okay")
    }
  return !rexp.test(fname)
}

Upvotes: 0

Related Questions