views:

265

answers:

3

I want to force the user to enter any combination of the following words. the words need to be comma delimited and no comma at the beginning or end of the string the user should only be able to enter one of each word.

Examples

admin
basic,ectech
admin,ectech,advanced
basic,advanced,admin,ectech

my attempt

^((basic|advanced)|admin|ectech)((,basic|,advanced)|,admin|,ectech){0,2}$

Thanks Marc

A: 

There's not really a good way to do this with regex, since regex doesn't really have a good way to handle "only allowed to enter a given word once" if there's no specific ordering required.

Amber
A: 

I would do a double attack on this. In your validation function, use a regex as well as a JavaScript hashtable to store words that have already been entered so as to prevent duplicates from being entered. My two cents while having a sip of coffee.

nickyt
A: 

I would suggest to split your requirement into several parts:

1) split the string using the str.split("[,]") and get an array of strings

2) validate each element of the array using expression like "^(bacic|advanced|..)$"

3) use hashtable to put each array element into that and if element is added more than once then fail validation

EDIT: Actualy in step 2 you can use another hashtable that will store all your words. It will be faster to check against hashtable than to run a regular expression.

Superfilin
Thanks for the helpful information, I think i will stick with what i have ^((basic|advanced)|admin|ectech)((,basic|,advanced)|,admin|,ectech){0,3}$ and allow duplicates