I have a regular expression that is in string form, I want to bind that regex to my grid cell. Such that, now the values in that cell are validated against that regex. I am using RegExp
JavaScript library for conversion and testing the value. But it is either returning false
everytime or giving me an invalid regex
, even for the simplest of the regex used.
This is the method I am using:
addCellValidator(columnObj[0].name, new CellValidator({
isValid: function (value) {
var regex = new RegExp("/^[a-zA-Z\-]+$/");
return value == "" || (regex.test(value));
}
}));
Is it the format or any special pattern required by the RegExp
?
I have a regular expression that is in string form, I want to bind that regex to my grid cell. Such that, now the values in that cell are validated against that regex. I am using RegExp
JavaScript library for conversion and testing the value. But it is either returning false
everytime or giving me an invalid regex
, even for the simplest of the regex used.
This is the method I am using:
addCellValidator(columnObj[0].name, new CellValidator({
isValid: function (value) {
var regex = new RegExp("/^[a-zA-Z\-]+$/");
return value == "" || (regex.test(value));
}
}));
Is it the format or any special pattern required by the RegExp
?
- what values are you testing against? – gmaliar Commented Feb 26, 2013 at 12:46
- Special characters in this case.. – faizanjehangir Commented Feb 26, 2013 at 12:48
2 Answers
Reset to default 6While this is valid JavaScript code:
new RegExp("/^[a-zA-Z\-]+$/")
... it doesn't generate the regular expression you think. It's equivalent to this:
/\/^[a-zA-Z-]+$\//
You'll have to:
- Strip delimiters
Extract and parse flags, if any, e.g.:
"/^[a-z-]+$/i" ---> new RegExp("^[a-z-]+$", "i")
One more note: there's no point in escaping -
with backslash. If want to match a literal -
inside a character class you need to put it as first or last item.
You just added the /
/
to the string, this works:
addCellValidator(columnObj[0].name, new CellValidator({ isValid: function (value) { var regex = new RegExp("^[a-zA-Z\-]+$"); return value == "" || (regex.test(value)); } }));