This is what is have tried
^(?=.(?=.?[+-,() ]))(?:\D*\d){3,15}\D*$
a regex that follows the following parameters:
Minimum length of digits not including special characters: 3
The maximum length of digits not including special characters: 15
The total number of digits has to be between 3,15
Space and Special characters allowed: '+', '-', '(', ')', ' '
No alphabets allowed
The length of the string is determined by the number of digits.
There can be n number of special characters in the string, but the length of the digit should not exceed 15.
The acceptable responses are
((((((((((12345 (Valid)
123---------------- (Valid)
123-5678-9123456 (Valid)
((((( (Invalid)
((((((((((123(Valid)
122!!!!!(invalid)
The regex used here is accepting the response when at least one special is present. However, if anything is present beside '+', '-', '(', ')', ' ' and digits, it's should not match
I would advise you not to try to do all the work with a single regular expression, but to break the check into multiple operations.
A complex regular expression is extremely difficult to maintain. Also, as far as I know, it's not posible to have a quantifier constraints for patter delimieted by some other pattern like (\d+(:ignore-this\D*)){3,15}. So I'm afraid you won't be able to reach the goal with a single regex.
But you can make your validation function like this and use it instead of regex test:
let targetList = [
'123',
'((((((((((12345',
'123----------------',
'12-------',
'123-5678-9123456',
'(((((',
'((((((((((123',
'122!!!!!'
];
function isValid(target) {
let hasInvalidChars = /[^\d\+\-() ]/
let hasSpecialChars = /[\+\-() ]/
let stripNonDigits = /\D+/g
let digitsCount = target.replace(stripNonDigits, '').length;
return (
!hasInvalidChars.test(target)
&& hasSpecialChars.test(target)
&& digitsCount >= 3
&& digitsCount <= 15
);
}
for (let target of targetList) {
console.log(target, isValid(target));
}
You can use
^(?:[(),+ -]*\d){3,15}[(),+ -]*$
See the regex demo. Details:
^ - start of string(?:[(),+ -]*\d){3,15} - three to fifteen sequences of a (, ), ,, +, space or - char and then any digit[(),+ -]* - zero or more chars from the (, ), ,, +, space or - charset.$ - end of string.