views:

135

answers:

4

Hi, I am trying to use regular expession in javascript but it is not working. My custom control contains property called RegEx which is provided by user and I need to validate the input value against this regex. As properties in JS will be in double quotes("") the regualr expression fails(case -1). Case 2 succeeds thought both the cases regualr expression is same, the only difference is case- 1 it goes as double quotes. can somebody tell me why it is not working. RegexExp="/^\d{5}$/"- at my aspx page

var value = "11111";
     if(value.toString().search($(element).attr('RegexExp')) != -1)
    {
        return true;
    }
    else
    {
        return false;
    }

  var reg = /^\d{5}$/;
     if(value.toString().search(reg) != -1)
    {
        return true;
    }
    else
    {
        return false;
    }
+2  A: 

Do this instead:

var reg = new RegExp($(element).attr('RegexExp'));

Update: you also need to strip the / characters, as these shouldn't be given to the RegExp constructor:

var regexExp = $(element).attr('RegexExp');
var reg = new RegExp(regexExp.substring(1, regexExp.length - 1));
Mark Byers
i tried the below sample example but still it is not working-var v1 = "22222";var reg = "/^\d{5}$/";reg = new RegExp(reg.substring(1, reg.length - 1));alert(v1.search(reg));it still gives -1
Punit
You can't do that because you need to escape backslashes in literal javascript strings, like this: var reg = "/^\\d{5}$/". But you don't need to escape the backslashes if you read the string directly from the page.
Mark Byers
+2  A: 

I assume that the code that you posted is part of the function from the return statements, but if it is not, your first problem is that return is not allowed to be used out side of functions.

In any case, try the following. You can create a RegExp from a string by using its formal constructor

value.search(new RegExp($(element).attr('RegexExp')));

Also, you do not need to use toString() on value since it is already a string and your code is unnecessarily verbose. The following is equivalent to your first if else statement

return value.search(new RegExp($(element).attr('RegexExp'))) != -1;


Edit:

If you want to be able to pass in an expression as "/[expression]/" or "/[expression]/gi", you can do the following:

var toRegExp = function(regexString) {
    var expression   = regexString.substr(1),        // remove first '/'
        closingSlash = expression.lastIndexOf("/");  // find last '/'

    return new RegExp(
        // Expression: remove everything after last '/'
        expression.substr(0, closingSlash), 
        // Flags: get everything after the last '/'
        expression.substr(closingSlash+1)
    );
}

....

value.search( toRegExp($(element).attr('RegexExp')) );
Justin Johnson
A: 

First, don't use a custom attribute to hold a regular expression. Second, "RegexExp" is redundant — that's like saying "regular expression expression". Third, to convert from a String to a RegExp, you have to wrap the string with new RegExp(); JavaScript is not weakly typed. That said, assuming that the regular expression isn't being set server-side, I'd recommend using jQuery's data API. It has the added advantage that it can store regular expression objects directly.

To set:

jQuery.data($(element).get(0), "regexp", /^\d{5}$/);

To get:

jQuery.data($(element).get(0), "regexp");

But ultimately, what you really want is the jQuery Validation plugin. It does everything you need and then some. Incidentally, it uses the data API internally to work its magic.

Bob Aman
Granted that depending on the available libraries there may be a better ways to do it, but there is nothing wrong with using a custom attribute to hold arbitrary data.
Justin Johnson
Woah, hey now... that -1 was uncalled for. The HTML specification does not allow custom attributes. What he's trying to do is guaranteed to make every page on which this technique occurs invalid. The work-around I gave is the generally accepted method of resolving the issue, and it has the added advantage of coming with all kinds of extras built-in, like email validation, credit card validation, and so on, most of which cannot be easily expressed with a simple regular expression. Have you seen the regular expression for emails? It's more than a full page long!
Bob Aman
Ya, email is ridiculous. I'll take it back since I suppose that I should have said that "there is nothing wrong with using a custom attribute," *if you specify a custom DTD*. For example: http://www.alistapart.com/articles/customdtd/
Justin Johnson
This is true, though honestly, even then, I still don't really recommend it in the general case because there's almost always a better alternative and the extra work of involving a custom DTD is rarely worth it.
Bob Aman
A: 

The /.../ syntax is used to declare a regular expression object in Javascript, so you shouldn't use that to specify a regular expression pattern, it should be just regexp="^\d{5}$" as the attribute.

The search method takes a regular expression object as parameter, so you have to create a regular expression object from the string that you get from the attribute:

var reg = new RegExp($(element).attr('regexp'));
if (value.toString().search(reg) != -1) {

(You see the similarity with your second case?)

Or as a single expression:

if (value.toString().search(new RegExp($(element).attr('regexp'))) != -1) {
Guffa