Necuima Posted October 22, 2014 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. Link to comment Share on other sites More sharing options...
HartleySan Posted October 22, 2014 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 Link to comment Share on other sites More sharing options...
Necuima Posted October 22, 2014 Author Share Posted October 22, 2014 Thanks HartleySan, your advice is always appreciated. Cheers from Oz. Link to comment Share on other sites More sharing options...
Larry Posted October 24, 2014 Share Posted October 24, 2014 Definitely agreeing with HartleySan here. Thanks! Link to comment Share on other sites More sharing options...
Recommended Posts