-1

Have following validation for year value from text input:

if (!year.match(new RegExp('\\d{4}'))){
    ...
}

RegExp equals null if numeric of digits from 0 to 3. It's OK.
In case 4 digits it returns value.It's OK.
In case more than 4 digits it returns value again,that it's NOT OK.

Documentation says {n} declaration means exact number,but works like:

exact+

With such ugly validation it work's fine:

if (!year.match(new RegExp('\\d{4}')) || year.length>4){
...
}

I wish to utilize RegExp object only.

sergionni
  • 13,290
  • 42
  • 132
  • 189
  • 2
    use delimiters so the regexp analyzer knows that it must be the whole string matching the expression, not just a part of it. ***^\\d{4}$*** – Alfabravo Dec 23 '11 at 09:23

4 Answers4

5

Yes it would allow more than 4 digits since it would be a partial match use the ^ and $ to mark the beginning and the end of the string.

if (!year.match(new RegExp('^\\d{4}$'))){
    ...
}
RageZ
  • 26,800
  • 12
  • 67
  • 76
3

If you include ^ in your regex it matches the beginning of the string, while $ matches the end, so all up:

^\d{4}$

Will match only against beginning-of-string plus four digits plus end-of-string.

Note that regex literal syntax is generally a bit simpler than saying new Regex():

/^\d{4}$/
// is the equivalent of
new RegExp('^\\d{4}$')

Note that in the literal syntax you don't have to escape backslashes like with the string you pass to the new RegExp(). The forward slashes are not part of the expression itself, you can think of them like quotation marks for regexes.

Also, if you just want to check if a string matches a pattern (yes or no) without extracting what actually matched you should use the .test() method as follows:

if (!/^\d{4}$/.test(year)) {
   ...
}
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
2

It's matching the first four digits and then the fact that there's any remaining digits it neither here nor there. You need to change your regex so it stops after these four digits, say, by using the string termination anchors:

^\d{4}$
Xophmeister
  • 8,884
  • 4
  • 44
  • 87
2

Try instead:

'^\\d{4}$'

What you had will match anything with 4 digits anywhere, such as asd1234asd or 123456789

Esailija
  • 138,174
  • 23
  • 272
  • 326