-3

Same question has been asked here: How to pass a regular expression as a function parameter, but I still can't get it work.

This is the string expression of regular expression that I used to test email:

var regexp="^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$";

and if I put it to firebug execute like this:

/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$"/.test("[email protected]")

it will give what I want,but If taking it as parameter to passing it to function:

function bool validate(var value, var regexp){
    //escape special characters
    regexp=String(regexp).replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').replace(/\x08/g, '\\x08');
    return new RegExp(regexp,'g').test(value)
}

like this:

 validate("[email protected]",regexp);

It will give me false.Please tell what mistakes I have made,thanks.

Update: sorry,as @Bhojendra - C-Link Nepal said,there is a typing mistake when translating gwt's jsni code to this,right code should be:

 function validate(value, regexp){
   //escape special characters
   var regexp = regexp.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').replace(/\x08/g, '\\x08');
    return new RegExp(regexp,'g').test(value);
}

but it doesn't work still.

2
  • I don't believe that validate(...) is returning false. The code will not execute at all because of the syntax error in function bool validate(var..., so it will generate a console error. You need to read up on basic JS syntax for defining functions. Please do not post questions with code which generates console errors, unless it is the console error itself which is stumping you. Commented Nov 20, 2014 at 4:03
  • Sorry,I actually translate this from my GWT's jsni function. Commented Nov 20, 2014 at 5:42

1 Answer 1

2

Replace this line:

function bool validate(var value, var regexp){

With this:

function validate(value, regexp){

And also after some modifications and typo fixes, here is the code:

function validate(value, regexp){
    //escape special characters
    var regexp = regexp.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').replace(/\x08/g, '\\x08');
    return new RegExp(regexp,'g').test(value);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.