tags:

views:

999

answers:

2

Hello All,

Using jQuery validation plugin but it has no CSV validation. I have made an additional validation for this but can't get the RegEx right.

Here is what I have:

jQuery.validator.addMethod("csv", function(value, element) {
return this.optional(element) || /([\w.$]+?(,[\w.]+)+)/.test(value);

}, "Must be comma separated if entering multiple values: value1,value2");

Any thoughts for the RegEx?

([\w.$]+?(,[\w.]+)+)

What I'm trying to do is have the user enter in a value, which can be a single value or multiple values in CSV format.

Example 1: value1

Example 2: value1,value2,etc... no limit

A: 

Maybe I'm not totally understanding what you need, but it seems like you could capture all the values with this regex:

/([^,]+),?/

This will allow spaces and special characters in the values, I'm not sure if you want that or not, since your attempt seemed to be trying to only allow word characters.

If you are just trying to check whether they entered something valid or not though, I'm not sure what you would want to consider "invalid". It seems to me that just about anything would be valid. If it doesn't have any commas, it's a single value. If it does, it's multiple values. Maybe if you give some more detail about what data you're expecting I can write a better validating expression.

Chad Birch
+1  A: 

Building on Chad's example, just switch [^,] to \w if you want only word characters. If you actually want just letters and digits, you'll need something like [a-z0-9] as \w includes the underscore character.

Based on your comment, see if

/^([a-z0-9])+(,[a-z0-9]+)*$/

does the trick.

Jon Freeland
works great for the first value but doesn't validate the second valueExample Value: 1,! <-- Should be invalid, but jQuery treats it as valid. Any thoughts?
Phill Pafford
Edited my answer, see if that works for you.
Jon Freeland
/^([a-zA-Z0-9])+(,[a-zA-Z0-9]+)*$/Thanks so much this works great!!!
Phill Pafford