1

a regex to show that there are at least 10 numeric characters in a string.

There can be more than 10, but not less. There can be any number of other characters in at random places, separating the numbers.

Example Data:

(123) 456-7890
123-456-7890 ext 41
1234567890
etc.
0

3 Answers 3

2

It's probably simplest to just get rid of all the non-numeric characters and count what's left:

var valid = input.replace(/[^\d]/g, '').length >= 10

NB: .replace doesn't modify the original string.

Sign up to request clarification or add additional context in comments.

Comments

1

For making sure at lest 10 digits are there use this regex:

/^(\D*\d){10}/

Code:

var valid = /^(\D*\d){10}/.test(str);

TESTING:

console.log(/^(\D*\d){10}/.test('123-456-7890 ext 41')); // true
console.log(/^(\D*\d){10}/.test('123-456-789')); // false

Explanation:

^ assert position at start of the string
1st Capturing group (\D*\d){10}
Quantifier: Exactly 10 times
Note: A repeated capturing group will only capture the last iteration.
Put a capturing group around the repeated group to capture all iterations or use a 
non-capturing group instead if you're not interested in the data
\D* match any character that's not a digit [^0-9]
Quantifier: Between zero and unlimited times, as many times as possible
\d match a digit [0-9]

2 Comments

I hate regexps. Even though I've used them for who knows how many years, it's not immediately 100% obvious how that works.
I added some explanation.
1
(\d\D*){10}

A digit followed by any number of non-digits, ten times.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.