Convert string to regex using regexp and test values in javascript - Stack Overflow

I have a regular expression that is in string form, I want to bind that regex to my grid cell. Such tha

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?

Share edited Jan 17, 2014 at 20:57 Jaak Kütt 2,6564 gold badges33 silver badges40 bronze badges asked Feb 26, 2013 at 12:43 faizanjehangirfaizanjehangir 2,8518 gold badges51 silver badges86 bronze badges 2
  • 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
Add a ment  | 

2 Answers 2

Reset to default 6

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:

  • 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)); }
            }));

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742404549a4437580.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信