0

I have an application to send TAN to users via SMS. We have already API to send SMS to a mobile phone number. Therefore, I have to make sure it's correct mobile phone number. Below is my regex:

function validateMobile(str) {

        var filter = /^\+?(\d[\d-. ]+)?(\([\d-. ]+\))?[\d-. ]+\d$/;

        if (!filter.test(str)) {
            alert('Please provide a valid mobile phone number');
            return false;
        }
        return true;
    }

It doesn't accept characters, only number and '+' allowed. Users can enter, for example +49176xxxxxxxx or 0176xxxxxxxx (no particular country code)

But this regex is seriously flawed. Users can enter whatever numbers, e.g. 1324567982548, this regex also returns true. I thought about to check the length of the textbox, it'd work, for the time being, but still it's not a proper solution.

Is there any other better regex or way to check more concrete a mobilbe phone number?

Thanks in advance.

SOLVED

I solved this with a new regex:

var filter = /^(\+49\d{8,18}|0\d{9,18})((,\+49\d{8,18})|(,0\d{9,18}))*$/;

or as mzmm56 suggested below:

var filter = /^(?:(\+|00)(49)?)?0?1\d{2,3}\d{8}$/;

Both are equally fine.

Ragnarsson
  • 1,715
  • 7
  • 41
  • 74

2 Answers2

0

It might be easier to to strip off all non-numeric characters (except + perhaps), then regex it, then if you need to output it, just reformat it.

Here's a regex for the phone number after non-numeric characters have been stripped:

^\+[1-9]{1}[0-9]{10}$

For more detailed info on country codes, see this post.

Community
  • 1
  • 1
Pat Lillis
  • 1,152
  • 8
  • 19
0

i think that you may need to restrict the regex to mobile number format of the country you're targetting, if possible, or check the input against a variety of patterns according to different countries' mobile number formats. it also seems like your regex would match .- instead of " only number and '+' ".

anyway—in Germany, i believe the following regex would work, only allowing a single + at the beginning, and then nothing but numbers:

^(?:(\+|00)(49)?)?0?1\d{2,3}\d{8}$

with 0?1\d{2,3} it's taking into account that German mobile numbers may or may not start with 0, begin with 1, and are followed by another 2 numbers (in your case 76), or 3 numbers (176) if there was no leading 0.

mzmm56
  • 1,264
  • 1
  • 14
  • 21
  • Hey, thanks. it works. Also, I came up with another regex, and it worked like yours var filter = /^(\+49\d{8,18}|0\d{9,18})((,\+49\d{8,18})|(,0\d{9,18}))*$/; – Ragnarsson Jul 03 '13 at 13:09