I am trying to validate a comma separated list of numbers 1-384 unique (not repeating).
i.e.
- 1, 2, 3, 5, 6, 7, 9 is valid
- 1-3, 5-7, 9 is valid
- 2, 2, 6 is invalid
- 2, is invalid
- 1, 2, 3, 4, 15, 6, 7, 385 is invalid because the last number is more than 384
I have tried the following RegEx pattern, but is not sufficient:
JavaScript
x
2
1
/^(?!.*(b(?:[1-9]|[1-2]d|3[0-1])b).*b1b)(?:[1-9]|[1-2]d|3[0-1])(?:,(?:[1-9]|[1-2]d|3[0-1]))*$/
2
Advertisement
Answer
You can try this-
JavaScript
1
62
62
1
function isValid(str) {
2
let lower = 1, upper = 384;
3
4
// Removing the unnecessary spaces
5
str = str.replace(/s/g, '');
6
7
// Split the string by comma (,)
8
const nums = str.split(',');
9
const track = {};
10
11
// Visit the numbers
12
for (const num of nums) {
13
14
// Check if any number contains a dash (-)
15
if (/-/.test(num)) {
16
17
// If has dash then split by dash and get the upper and lower bounds.
18
const [l, u] = num.split('-').map(x => x * 1);
19
20
// Visit from lower to upper bound
21
for (let i = l; i <= u; i++) {
22
23
// If any number of the range doesn't exceed the upper
24
// or lower bound i.e. [1, 384] range and did not
25
// appear before then track this number.
26
// otherwise return false i.e. mark it as invalid.
27
if (i >= lower && i <= upper && track[i] === undefined) {
28
track[i] = true;
29
} else {
30
return false;
31
}
32
}
33
34
} else {
35
36
// Checking again if it exceed the range [1, 384] or appears before.
37
if (num * 1 >= lower && num * 1 <= upper && track[num] === undefined) {
38
track[num] = true;
39
} else {
40
return false;
41
}
42
}
43
}
44
45
// If everything okay then return true, i.e. valid.
46
return true;
47
}
48
49
const strs = [
50
'1, 2, 3, 5, 6, 7, 9',
51
'1-3, 5-7, 9',
52
'2, 2, 6',
53
'2,',
54
'1, 2, 3, 4, 15, 6, 7, 385',
55
'1-4, 3, 7-9, 10',
56
'1-100, 102, 123',
57
'1-100, 102, 99'
58
];
59
60
for (const str of strs) {
61
console.log(str + ' => ' + (isValid(str) ? 'Valid': 'Invalid'));
62
}
JavaScript
1
1
1
.as-console-wrapper{min-height: 100%!important; top: 0}