Created
October 10, 2018 09:34
-
-
Save AnowarCST/890ea6c5bda2137758d258904a8b215a to your computer and use it in GitHub Desktop.
Validate local and international mobile no. Extract local mobile no.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Requests; | |
class MobileNumberValidator | |
{ | |
/** | |
* Validate local/international Mobile No | |
* | |
*/ | |
private $local_regex = '/^(?:\+88|01)?(?:\d{11}|\d{13})$/'; | |
// reference: https://stackoverflow.com/a/6967885 | |
private $international_regex = '/\+(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d| | |
2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]| | |
4[987654310]|3[9643210]|2[70]|7|1)\d{1,14}$/'; | |
private $prefix_regex = '/^(\+88|88|0088)?(01[135-8])/'; | |
/** | |
* Validate the number | |
* @param $mobile_no | |
* @return array | |
* is_valid: true/false | |
* validation type: local, international, null | |
* operator_code: 017/018/016 | |
*/ | |
public function validate($mobile_no) | |
{ | |
$mobile_no = preg_replace("/[^0-9+]/", '', $mobile_no); //removing all non numeric characters | |
$returnable = [ | |
'is_valid' => false, | |
'type' => '', | |
]; | |
if(empty($mobile_no)) { | |
$returnable = [ | |
'is_valid' => false, | |
'type' => 'empty', | |
]; | |
return $returnable; | |
} | |
if (preg_match($this->local_regex, $mobile_no, $match)) { | |
$prefix = []; | |
if (preg_match($this->prefix_regex, $mobile_no, $getPrefix)) { | |
$prefix = [ | |
'operator_code' => $getPrefix[2], | |
// 'mobile_no' => $mobile_no, | |
// 'operator_code' => $getPrefix[1], | |
]; | |
} | |
$returnable = [ | |
'is_valid' => true, | |
'type' => 'local', | |
'mobile_no' => $mobile_no, | |
] + $prefix; | |
} elseif (preg_match($this->international_regex, $mobile_no)) { | |
$returnable = [ | |
'is_valid' => true, | |
'type' => 'international', | |
'mobile_no' => $mobile_no, | |
]; | |
} | |
return $returnable; | |
} | |
} | |
/** | |
* Uses: | |
* | |
* $mobile_no = '+8801822 141954'; | |
* return (new \App\Http\Requests\MobileNumberValidator())->validate($mobile_no); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment