Necuima 18 Posted October 22, 2014 Report Share Posted October 22, 2014 Hi, I have a form field that needs to be validated before any attempt is made to upload the contents to a database. Fear not, the test is performed again in PHP before the db update! I am using jQuery and the associated jQuery form validation module. Everything works fine but I have found that three slightly different regular expression tests can be used - my question is: are there any performance or other reasons why one particular approach is best? Here's the code together with an explanation of the regex: $.validator.addMethod( "details_OK", function (value, element) { var valx = String(value); // var regex_tester = new RegExp( var regex_tester = /^(http:\/\/)(\S)+(\?u=){1}(\S)+(\&id=){1}(\S)+(\&e=){1}(\S)+/; /* var regex_tester = / // must start with what follows "^" + // now the http bit... "(http:\/\/)" + // any letters, numbers or periods (one or more of them) "(\\S)+" + // must contain ?u= (once) "(\?u=){1}" + // now more letters, numbers etc.. "(\\S)+" + // now &id= (once) "(\&id=){1}" + // now more letters, numbers etc.. "(\\S)+" + // now &e= (once) "(\&e=){1}" + // now more letters, numbers etc.. "(\\S)+" + /; */ // Note: all 3 of the following tests work OK... // if (regex_tester.test(valx)) // if (/^(http:\/\/)(\S)+(\?u=){1}(\S)+(\&id=){1}(\S)+(\&e=){1}(\S)+/.test(valx)) if (valx.match(/^(http:\/\/)(\S)+(\?u=){1}(\S)+(\&id=){1}(\S)+(\&e=){1}(\S)+/)) return true; else return false; }, "Error - The Internet address (URL) does not have some of the required/expected details." ); // end details check I could not get the "...new RegExp approach to work thus it is commented out. Any thoughts/advice will be most appreciated. Thanking you in anticipation, Cheers from Oz. Quote Link to post Share on other sites
HartleySan 826 Posted October 22, 2014 Report Share Posted October 22, 2014 Use the test method when you just want to check for a match, and use match when you actually want to get the match(es) back. The literal syntax (i.e., //) will always be faster than the new RegExp syntax, and as such, I only use new RegExp when I need to embed a variable in my regex. 1 Quote Link to post Share on other sites
Necuima 18 Posted October 22, 2014 Author Report Share Posted October 22, 2014 Thanks HartleySan, your advice is always appreciated. Cheers from Oz. Quote Link to post Share on other sites
Larry 429 Posted October 24, 2014 Report Share Posted October 24, 2014 Definitely agreeing with HartleySan here. Thanks! Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.