Sylnois
Sylnois

Reputation: 1631

Regex: Only numbers or empty string

I have a telephone input field. You should only type numbers, spaces or leave it empty. An idea how to build the regex?

Upvotes: 1

Views: 6044

Answers (2)

anubhava
anubhava

Reputation: 786291

You can use this regex:

/^[\d\s]*$/

Upvotes: 2

Tim Pietzcker
Tim Pietzcker

Reputation: 336478

The regex would be

^[\d ]*$      # in JavaScript, that's /^[\d ]*$/

but I would not do it this way. You should allow all characters, then filter out the numbers in a second step, using something like result = subject.replace(/\D+/g, "");.

Reason: People have all kinds of ways to enter phone numbers (1-(123) 343-2345 etc.), and they don't like it if a website tells them the number is incorrect.

Are you aware that you're excluding country codes with this requirement? I have all my phone numbers stored as +49 123 456-7890, and I wouldn't like my country code to be mistaken for an area code.

Upvotes: 4

Related Questions