Jump to content

validating a 7-digit phone number


peppericious

Recommended Posts

I know this should be easy.... However, to validate a 7-digit phone number, I wrote this:

 

<?php
if(!empty($_POST['mobile_number'])) {
          if(!is_numeric($_POST['mobile_number']) || strlen($_POST['mobile_number']) != 7) {
            $errors[] = 'Please enter a 7-digit number without spaces or dashes for your <strong>Mobile</strong>.';
          } else {
            $_SESSION['mobile_number'] = $_POST['mobile_number'];
          }
      } else {
        $_SESSION['mobile_number'] = '';
      }

 

... but now I realise that numeric/integer validation won't work because where I am - in Ireland - mobile numbers can start with an initial zero, too. So, the following mobile numbers are possible:

  • 0123456
  • 0224466

 

How can I ensure that:

[*]each digit in the mobile number is numeric

[*]an initial zero is possible

[*]there are exactly 7 digits

 

I suppose I loop through each digit, ensuring that that digit is numeric and break out of the loop if a non-numeric digit is encountered..?

Any suggestions?

 

TIA

Link to comment
https://forums.phpfreaks.com/topic/258643-validating-a-7-digit-phone-number/
Share on other sites

Russ, much better!!! Can you explain what the dollar sign indicates?

 

the ^ denotes start, and $ denotes end

 

if you're in multiline mode, ^ is the start of the string, and $ is the end of a string, however if you're not in multiline (dot all), then ^ is the start of a line, and $ is the end of a line..

 

so if you supply a string like:

 

'abc123'

 

a pattern like: '/.$/' will match '3'

 

:) Hope I helped!

 

Russell

There's no need for a regex pattern to do what you want to do. I'm not sure why you think a leading zero makes a difference. It shouldn't matter because all form values are sent as strings anyhow.

 

if( ctype_digit($number) && strlen($number) === 7 ) {
     // number is valid
}

There's no need for a regex pattern to do what you want to do. I'm not sure why you think a leading zero makes a difference. It shouldn't matter because all form values are sent as strings anyhow.

 

if( ctype_digit($number) && strlen($number) === 7 ) {
     // number is valid
}

 

Yes, thanks, you're quite right.

 

In fact, I had defined the db fields as integers and consequently the leading zeroes were being truncated. When I changed the fields in the db to text, there was no further problem.

 

Thanks for showing me that ctype_digit function: useful to know in any case.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.