0

I'm having problems with regex and can't get a value to be validated.

I have a function like this:

function validationObject(validationName, validationRegEx) {
     this.validationName = validationName;
     this.validationRegEx = validationRegEx;
}

It creates a validationObject with the parameters it gets. For a dropdownlist containing a number I have this regex:

\d+

But when I validate the value with this regex with this piece of code it won't work:

if (inputValue.match(validatingRegex)) {
     doSomeThings();
} 

If I check for the validationObject I see that Chrome has changed the regex to /d+/ . I've tried setting it to a regex-type, but it doesn't work either. This does work on textfields. It seems to me that all backslashes get converted to something else.

Also I've tried escaping the backslash but then the browser just takes the literal value.

Hopefully you have an answer, thanks for your help!

Best regards,

Boyyerd

1 Answers1

1

you need to escape special chars if you're passing them to the RegExp constructor:

var expr = new RegExp(somStr.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), 'i');

Since you're passing \d+, the backsash needs escaping, so you should be possing \\d+ to the constructor.
The regex above escapes all special chars AFAIK. I've taken the liberty of copying the expression from here.
An alternative, and easier way to create the expression is to use the literal notation, which is far more common, more in tune with JS, and less error-prone:

var expr = /\d+/;

No need to escape a string at all.

You can easily check this in your console btw: '\d' evaluates to "d" in chrome console, so passing '\d+' to RegExp evaluates to new RegExp('d+'), which is a valid regex, so no errors are thrown, it just doesn't do the same thing.

A side-note, though: could you clarify what the goal of your function is, exactly, because it's no constructor (if it is, its name should start with an UpperCase letter), and I don't think you fully understand what the this reference can/will do in your case

Community
  • 1
  • 1
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
  • @Boyyerd: Please do consider the notes on your use of the `this` reference. My guess is, if you were to write `"use strict";` on the first line of either your entire script, or even as the first statement in your function, your script will fail: implied globals, using `this` reference to refer to the global object... – Elias Van Ootegem Aug 13 '13 at 09:25