2

I have a CMS app that allows custom fields to be added. One type of custom field is a user text input box. When creating this field type you can also supply a perl regex for use in the preg_match php function to validate user input for this field.

Now I'm setting up new way of administrating the data with lots of front end jquery fanciness and I'm running into this issue. When the form is generated dynamically (ajax/php) a JSON string is also assembled and added to the ajax repsonse data for along with the dynamic form HTML. The receiving javascript function paints the html and parses the JSON string that contains information on the fields (what type of field it is: text or select along with other field options present for each field. This JSON object is then attached to the jQuery data() method of the #submitButton of the form.

When the user submits the form, the data() keys of the button are looped to access the information about which form id's should be checked for input validation, ie selectindex cant be zero and text fields must validate against the supplied regex pattern.

The regex pattern I've supplied for the PHP end of things is: /^([A-Za-z0-9 .\-']*)$/ and this has been working great in php, and the rest of what I described is working great as well. My problem is that I'm really not good at regex and I do not uderstand why this pattern matches correctly via preg_match in php but using string.match(pattern); in javascript is failing every time, no matter what input I give it.

Here is a snippet of code:

var checklist = $('#ficb1').data(); // gets data() object.
var errors = new Array();
for(var key in checklist) { // loop through data() keys

        // verify text field
        if(checklist[key]["type"] == "text") { // do the following for text fields
            if(checklist[key]["options"]) { // checks if a pattern is set
                // found pattern! regex check!
                var pattern = checklist[key]["options"]; // verfied value: /^([A-Za-z0-9 .\-']*)$/
                var valstr = $('#'+key).val(); // key = id of field being checked without # sign valstr varified to hold the value of the input text.
                if(!valstr.match(pattern)) {
                                            // add error message to error array - regex match not found.
                    var engkey = key.replace('_', ' ');
                    errors.push(ucfirst(engkey.substr(1)) + ' did not match the required pattern ('+pattern+').');
                }
            }
        }

}

No matter what I input, the function ends up adding that text to the error erray, even when I enter in "hello" without quotes, which should match that regex...

Sorry for the long-winded explanation, what am I doing wrong with this regex matching?

7
  • Is pattern not just a string? Shouldn't you use new RegExp(pattern) instead? Commented Aug 14, 2011 at 6:50
  • 1
    @Bart, actually no, String.match is tolerant: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… Commented Aug 14, 2011 at 6:59
  • @SubkymeRick, can you alert the value of valstr before the match? Commented Aug 14, 2011 at 6:59
  • @Ray: But if the string is "/^.../" rather just "^..." it won't work as expected. Commented Aug 14, 2011 at 7:01
  • 1
    @Ray: I'm pretty sure you can put RegExp objects in jQuery data but we don't know how the data was initialized and the regular expression is fine as far as JavaScript is concerned. And it is easy to mix up a regex and a string by dumping them to the console. Commented Aug 14, 2011 at 7:11

1 Answer 1

3

I'm guessing that your regular expression is a string like this:

"/^([A-Za-z0-9 .\-']*)$/"

and that won't work as a regular expression. Try removing the leading and trailing slashes before you insert it into your JavaScript.

Open up your JavaScript console and see what this does to see the difference some slashes can make:

var pat = "^([A-Za-z0-9 .\\-']*)$";
console.log('pancakes'.match(pat));
console.log('pancakes'.match(new RegExp(pat)));
console.log('pancakes'.match(/^([A-Za-z0-9 .\-']*)$/));

var pat2 = "/^([A-Za-z0-9 .\\-']*)$/";
console.log('pancakes'.match(pat2));
console.log('pancakes'.match(new RegExp(pat2)));

Or go here: http://jsfiddle.net/ambiguous/7FPux/

Sign up to request clarification or add additional context in comments.

2 Comments

It appears the problem was the string version of the pattern was breaking it. I had to remove the first / and the last / from the pattern string, then ran that through new RegExp(); The output from that worked the way I wanted it to! Thanks for the help guys!
@Ray: Not quite as cool as "String is not equal to itself" but a fun problem none the less.

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.