January 30th, 2012, 03:41 PM

Regex for validating multiple numbers?
I hav tried this:
regex=/^(([19][09]*)0)(,(([19][09]*)0))*$/;
And that validates all numbers separated with comma...
Now I want to evolve that thought
Now I want to validate a given string of numbers!
I have a string that I fetch from db.
The string contains numbers.
The numbers is connected to the user so the validation is to check if so the user only enter numbers connected to that specific user.
How do I write a regex so that the input matches one or more of the numbers in the string?
All numbers entered in the input must be in the string.
The input must have the form number,number,number,...,...
That is: number followed by comma, no spaces or other chars...
Thanx in advance!
January 30th, 2012, 11:44 PM

This is probably what you want:
Code:
/^(12345678)(,(12345678))*$/
123, 456, and 78 are the allowed numbers; their order does not matter in the input string. But if the allowed numbers are taken from database, then it's easier to split the input by comma (using explode() function in PHP) and compare each number against the set of allowed numbers.
January 31st, 2012, 09:47 AM

[resolved]
Thanx!
It seems like it works
I'll be back if I find some errors
Thanx again!
February 2nd, 2012, 09:10 AM

Ok!
Now I have a follow up question
If I want to validate so that each number only can be in input once, how do I do that?
February 2nd, 2012, 06:50 PM

Originally Posted by marcushjortsber
If I want to validate so that each number only can be in input once, how do I do that?
Hi Marcus,
Not a problem!
Let's just add some conditions to aba's expression: at the front, for each number, we add a lookahead that checks the number is not present in the string twice.
Code:
^(?!.*?123.*?123)(?!.*?456.*?456)(?!.*?78.*?78)(12345678)(,(12345678))*$
If you have numbers that can be embedded in other numbers (for instance, 78 and 782 are both possible), then we need to refine that by adding word boundaries:
Code:
^(?!.*?\b123\b.*?\b123\b)(?!.*?\b456\b.*?\b456\b)(?!.*?\b78\b.*?78)(12345678)(,(12345678))*$
I know you know that, but for the record for someone who might be studying regex on the thread: If you have an array of numbers, it's a simple task build the regex programmatically.
Wishing you a fun day.
February 2nd, 2012, 07:28 PM

Hi again Marcus,
Do note that at the moment, the regex doesn't specify how many numbers your user should input, so unless you enforce this beforehand, s/he can get away with inputting a single number, e.g. 11
If you'd like to check that at least two numbers are present, you can add another lookahead:
Code:
^(?=(?:\d+(?:,$)){2})(?!.*?\b11\b.*?\b11\b)(?!.*?\b55\b.*?\b55\b)(?!.*?\b64\b.*?\b64\b)((?:115564)(?:,$))++$
Just change the {2} to the minimum number of numbers you require.
Note slight tweaks also in the matching part of the expression (after the lookaheads).