sab669 - 1 year ago 43

Javascript Question

I need to ensure a field on my form contains **only** alphanumeric characters. Zero through Nine, A through Z. No punctuation, no special characters, nothing else.

I have the following method:

`function foo()`

{

var pStrValue = mTrim($('#txtIDNumber').val());

var regexFirstChar = new RegExp("^[A-Z0-9]{1}"); //First character is alphanumeric

var regexNum = new RegExp("^[0-9]{9}.{0,3}$"); // First 9 are numeric

var regexLetter1 = new RegExp("^[A-Z]{1,3}[0-9]{6}$"); //Up to the first 3 are alpha, then there are exactly 6 numbers

var regexLetter2 = new RegExp("^[A-Z]{1,3}[0-9]{9}$"); //Up to the first 3 are alpha, then there are exactly 9 numbers

var firstCharIsNum = !isNaN(pStrValue.charAt(0));

if (!regexFirstChar.test(pStrValue)) //If the first character isn't alphanumeric

return false;

else if (firstCharIsNum)

{

//this is the conditional that evaluates to true incorrectly

if (!regexNum.test(pStrValue)) //If the first character is a number and is not proceeded by 8 more digits

return false;

}

else if (!firstCharIsNum)

{

if (!regexLetter1.test(pStrValue) && !regexLetter2.test(pStrValue)) //If the first 1-3 characters are letters and are not proceed by exactly 6 or 9 digits

return false;

}

return true;

}

The problem is that this is accepting special characters. I entered

`1234567890”,’”`

I wrote this a year ago and it was definitely working then (or I suppose perhaps QA missed this), but since then our application has gone under a

Answer Source

If I understand your goal correctly, the problem is in your line:

```
var regexNum = new RegExp("^[0-9]{9}.{0,3}$");
```

The `.`

allows *any* character between zero and three times. At a minimum, you need to escape it as `\.`

-- but I think what you're really looking for is (for nine digits before the decimal point, and three digits after):

```
var regexNum = new RegExp("^[0-9]{9}\.[0-9]{0,3}$");
```