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?
While 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:
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)); } }));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With