-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #139 from Jhnbrn90/master
Added phone number validation in PHP
- Loading branch information
Showing
2 changed files
with
49 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -82,3 +82,8 @@ Programming Language: Java, C, HTML, CSS, Kotlin | |
Email: [email protected] | ||
|
||
|
||
Name: [John Braun](https://github.com/jhnbrn90) | ||
About: I am doing a PhD in organic chemistry and really like programming. Used Laravel to create some useful tools for our research group, amongst others a chemicals inventory, booking system and supporting information manager. | ||
Programming Language: PHP, JavaScript | ||
Email: [email protected] | ||
|
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
<?php | ||
|
||
/** | ||
** Phone number validator | ||
** based on the JS validator regex. | ||
** In this example, 2-123-123-1231 will return true | ||
*/ | ||
|
||
class PhoneNumber | ||
{ | ||
protected $phoneNumber; | ||
|
||
protected $regex = '/^\d(?:-\d{3}){3}\d$/'; | ||
|
||
/** | ||
* PhoneNumber constructor. | ||
* @param $phoneNumber | ||
*/ | ||
public function __construct($phoneNumber) | ||
{ | ||
$this->phoneNumber = $phoneNumber; | ||
} | ||
|
||
/** | ||
* Validate the passed in phone number | ||
* using the defined regex | ||
* @return bool | ||
*/ | ||
public function validate() | ||
{ | ||
preg_match($this->regex, $this->phoneNumber, $matches); | ||
return !empty($matches); | ||
} | ||
} | ||
|
||
// Register a new phone number | ||
$phoneNumber = new PhoneNumber('2-123-123-1231'); | ||
|
||
// validate the phone number, returning a boolean | ||
$phoneNumber->validate(); | ||
|
||
// return a statement (string) based on the boolean value | ||
echo $phoneNumber->validate() ? 'Valid phone number :-)' : 'Invalid phone number :-('; | ||
|