Here is My working Code, if you got a better one post below.
Took me hours to build.
Number can be between (4-15) Universal Standard.
Might contain '+' at the beginning and '-' is allowed once with allowed format like ('1+123,12+123,+1-123,+12-123).
Rest all spaces and '-' and '+' will be replaced by blank and a proper Number will be returned.
public function validateMobileNumber($mobile){
$mobile = str_replace(' ','',$mobile);//remove all the blank spaces i.e +1-123456342234
//now let's do it for mobile numbers
if(preg_match('/^([0-9,\\-,+,]){4,15}$/', $mobile)){//pratially valid number
$mobile = rtrim($mobile, "+");
$mobile = trim($mobile, "-");
//removing multiple '-'
$mobile_arr = explode('-',$mobile);//elplode a number like +1-123 456-342-234
$sub1 = $mobile_arr[0];//+1
if(strlen($sub1) != strlen($mobile)){ // condition where 12345678 valid nos is detected
$check_plus = explode('+',$sub1); //logic to detect number starts with +1-123.. or +12-123.. or 1-123.. or 12-123...
if($check_plus[0] == ''){ // occurs when we get +1...
if(strlen($sub1) == 2 || strlen($sub1) == 3){//valid digits like +1-123, +12-123
unset($mobile_arr[0]);
} else {
//invlid number
return array('status'=>'error','message'=>'Number must be in +1-123.. or +12-123.. or 1-123.. or 12-123... format');
}
} else {
if(strlen($sub1) == 1 || strlen($sub1) == 2){//valid digits like 1-123, 12-123
unset($mobile_arr[0]);
} else {
//invlid number
return array('status'=>'error','message'=>'Number must be in 1-123.. or 12-123.. or +1-123.. or +12-123... format');
}
}
$mobile = $sub1 .'-'.implode('',$mobile_arr);//+1-123 456342234
}
//removing '-' ends
//removing '+'
$mobile_arr = explode('+',$mobile);//explode a number like +1-123 456+342-234
if($mobile_arr[0]!='') {
if (strlen($mobile_arr[0]) != strlen($mobile)){ //number might be 1-123 456+342-234+
return array('status'=>'error','message'=>'Number must have "+" at the start ');
}
} else {
if($mobile_arr[2]!=''){//when we have more than one +
$sub1 = $mobile_arr[1];
unset($mobile_arr[1]);
$mobile = '+'.$sub1.implode('',$mobile_arr);//+1-123 456342234
}
}
return array('status'=>'success','data'=>$mobile);
} else {
return array('status'=>'error','message'=>'Invalid Mobile Number.');
}
//Validate Mobile number logic ends
}
Related
I am trying to validate a phone number using PHP, and would like to know if there's a way to do it with FILTER_SANITIZE_NUMBER_INT instead of regex.
I need the password to enforce the xxx-xxx-xxxx format (allows '-') and max length of 12 characters.
This is my code so far. Would this work to validate any number into the xxx-xxx-xxxx format?
$phone = clean_input($_POST["phone"]);
if (empty($phone)) {
$phoneErr = "Valid phone number required";
$isValid = false;
} else {
if (!filter_var($phone, FILTERSANITIZE_NUMBER_INT)) ;
$phone_to_check = str_replace("-", "", $filtered_phone_number);
if (strlen($phone_to_check) < 10 || strlen($phone_to_check) > 12) {
$isValid = false;
}
}
I would use preg_match instead as you can cover all your needs in one statement. This regex assures that the value must have 10 digits, with optional - after the third and sixth digits.
$phone = clean_input($_POST["phone"]);
$isValid = preg_match('/^\d{3}-?\d{3}-?\d{4}$/', $phone);
Demo on 3v4l.org
I prefer using preg_match() functions for this style of regex.
An example based on your pattern
$phone = '000-000-0000';
if(preg_match("/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/", $phone)) {
// $phone is valid
}
For validating using FILTER_SANITIZE_NUMBER_INT() try code below
function validate_phone_number($phone)
{
$filtered_phone_number = filter_var($phone, FILTER_SANITIZE_NUMBER_INT);
if (strlen($filtered_phone_number) < 12) {
return false;
} else {
return true;
}
}
Now below is the usage of the function that we have just created:
$phone = "444-444-5555";
if (validate_phone_number($phone) == true) {
echo "Phone number is valid";
} else {
echo "Invalid phone number";
}
I'm using the Contact Form 7 plugin on wordpress to collect data inputted in the fields, I'm now looking to set up some validation rules using this neat extension: http://code-tricks.com/contact-form-7-custom-validation-in-wordpress/
What I'm after is to only allow one word only in the text field (i.e. no whitespace) and this one word has to begin with the letter 'r' (not case sensitive).
I've written the no white space rule as follows:
//whitespace
if($name == 'WhiteSpace') {
$WhiteSpace = $_POST['WhiteSpace'];
if($WhiteSpace != '') {
if (!preg_match('/\s/',$WhiteSpace)){
$result['valid'] = true;
} else {
$result['valid'] = false;
$result['reason'][$name] = 'Invalid Entry.';
}
}
}
Is it possible to incorporate the second rule into this also? So no whitespace, and the word must begin with the letter 'r'? Any suggestions would be greatly appreciated!
EDIT:
seems core1024 answer does work, but only one of them:
//FirstField
if($name == 'FirstField') {
$FirstField = $_POST['FirstField'];
if($FirstField != '') {
if (!preg_match("/(^[^a]|\s)/i",$FirstField)){
$result['valid'] = true;
} else {
$result['valid'] = false;
$result['reason'][$name] = 'Invalid Entry.';
}
}
}
//__________________________________________________________________________________________________
//SecondField
if($name == 'SecondField') {
$SecondField = $_POST['SecondField'];
if($SecondField != '') {
if (!preg_match("/(^[^r]|\s)/i", $SecondField)) {
$result['valid'] = true;
} else {
$result['valid'] = false;
$result['reason'][$name] = 'Invalid Entry.';
}
}
}
I want to use this code twice, once to validate the first character being a on one field the second instance with the first character being r on another field. But it only seems the SecondField validation rule is working.
Try to use:
preg_match('/^r[^\s]*$/i',$WhiteSpace)
instead of:
!preg_match('/\s/',$WhiteSpace)
You need this:
if (!preg_match("/(^[^r]|\s)/i", $WhiteSpace)) {
It matches any string that doesn't start with r/R or contain space.
Here's a test:
$test = array(
'sad',
'rad',
'ra d'
);
foreach($test as $str) {
echo '"'.$str.'" -> '.preg_match('/(^[^r]|\s)/i', $str).'<br>';
}
And the result:
"sad" -> 1
"rad" -> 0
"ra d" -> 1
I have magento, and I'm posting a request via the soap v2 api to get the address of an order.
With that I get the following object which contains the street name + housenumber(God knows why these fields are not seperate...)
$shipping_address->street = "4th avenue 108";
Now what I want is to have the housenumber 108.
How do I get this house number without getting the 4?
(if someone has a more reliable function/piece of code than the one I post below, please feel free to post it.)
What you basically have to do is check for the first number occurence with a space in front of it.
This way you minimse the risk of fetching the wrong number:
// Code by Michael Dibbets
// shared under creative commons Attribution 3.0 Unported (CC BY 3.0 http://creativecommons.org/licenses/by/3.0/ )
$value = "4th street26";
$spl = str_split($value);
$pos = 0;
$location = 0;
// simple loop to find the first character with space + integer
foreach($spl as $char)
{
if(is_numeric($char) && $spl[$pos-1]==' ')
{
$location = $pos;
break;
}
$pos++;
}
// If we didn't encounter the space + integer combination
if(!$location)
{
// is the last character an integer? Assume that the last numbers are house numbers
if(is_numeric($spl[count($spl)-1]))
{
for($c=count($spl)-1;$c>0;$c--)
{
if(is_numeric($spl[$c]))
{
continue;
}
else
{
$location = $c+1;
break;
}
}
}
}
if($location)
{
$street = substr($value,0,$location);
$number = substr($value,$location);
}
else
{
$street = $value;
$number = null;
}
// echoing the results. The number should appear after the dash.
echo $street . ' - ' . $number;
I am looking for a simple regex to convert both UK (44) and Indian (91) numbers into a valid international format using PHP. The formats required are:
447856555333 (for uk mobile numbers)
919876543456 (for indian mobile numbers)
I need a regex that will accept and format the following variations:
1) 07856555333
2) 0785 6555333
3) 0785 655 5333
4) 0785-655-5333
5) 00447856555333
6) 0044785 6555333
7) 0044785 655 5333
8) 0044785-655-5333
9) 00447856555333
10) +447856555333
11) +44785 6555333
12) +44785 655 5333
13) +44785-655-5333
14) +919876543456
15) 00919876543456
Any help would be much appreciated.
UPDATE: Based on answer below I have amended the code slightly and it works very well. It is not bullet proof but covers most of the popular formats:
public static function formatMobile($mobile) {
$locale = '44'; //need to update this
$sms_country_codes = Config::get('sms_country_codes');
//lose any non numeric characters
$numeric_p_number = preg_replace("#[^0-9]+#", "", $mobile);
//remove leading zeros
$numeric_p_number = preg_replace("#^[0]*#", "", $numeric_p_number);
//get first 2 digits
$f2digit = substr($numeric_p_number, 0,2);
if(strlen($numeric_p_number) == 12) {
if(in_array($f2digit, $sms_country_codes) ) {
//no looks ok
}
else {
return ""; //is correct length but missing country code so must be invalid!
}
}
else {
if(strlen($locale . $numeric_p_number) == 12 && !(in_array($f2digit, $sms_country_codes))) {
$numeric_p_number = $locale . $numeric_p_number;
//the number is ok after adding the country prefix
} else {
//something is missing from here
return "";
}
}
return $numeric_p_number;
}
for your particular scope think something like this might work ... not really a regex-only solution but should do the trick for your needs:
$locale = "your_locale_prefix";
$valid_codes = array("44","91");
//loose any non numeric characters
$numeric_p_number = preg_replace("#[^0-9]+#", "", $phone_number);
//remove leading zeros
$numeric_p_number = preg_replace("#^[0]*#", "", $numeric_p_number);
//get first 2 digits
$f2digit = substr($numeric_p_number, 0,2);
if(in_array($f2digit, $valid_codes) && strlen($numeric_p_number) == 12){
//code is ok
} else {
if(strlen($locale . $numeric_p_number) == 12) {
//the number is ok after adding the country prefix
} else {
//something is missing from here
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Regular Expression matching for entire string
On my form page, I am trying to make it only accept alphanumeric characters for my username and password and require that they be from 6 to 15 characters. When I type in invalid data, it will insert it into the database rather than throw the user error that I defined in my CheckAlNum function.
functions.php
function checkAlNum($whichField)
{
if (preg_match('/[A-Za-z0-9]+/', $_POST[$whichField])){
if ( (!count(strlen($whichField) >= 6)) OR (!count(strlen($whichField) <= 15 ))) {
$message1 = '<p> Username and password must be between 6 and 15 characters </p>';
return user_error($message1);
}
else{
return true;
}
}
else {
$message = '<p>Username and password can only be numbers or letters</p>';
return user_error($message);
}
}
Form.php
if (count($_POST) > 0) {
//Validate the inputs
$errorMessages = array();
//Validate the username
$item5 = checkAlNum('username');
if($item5 !== true) {
$errorMessages[] = $item5;
}
//Validate the password
$item6 = checkAlNum('password');
if($item6 !== true) {
$errorMessages[] = $item6;
}
//Validate the firstName and lastName
$item1 = checkNameChars('firstName');
if ($item1 !== true) {
$errorMessages[] = $item1;
}
$item2 = checkNameChars('lastName');
if ($item2 !== true) {
$errorMessages[] = $item2;
}
//Validate the office name
$item3 = checkOfficeChars('office');
if ($item3 !== true) {
$errorMessages[] = $item3;
}
//Validate the phone number
$item4 = validate_phone_number('phoneNumber');
if($item4 !== true) {
$errorMessages[] = $item4;
}
//Check to see if anything failed
if (count($errorMessages) == 0) {
$newEmployee = new Person;
$newEmployee -> insert();
}
else { //Else, reprint the form along with some error messages
echo "<h2><span>Error</span>: </h2>";
foreach($errorMessages as $msg) {
echo "<p>" . $msg . "</p>";
}
}
}
?>
I've tried playing around with the nesting of the if-else statements of the checkAlNum function and also the regex (although I'm pretty sure the regex is right). Maybe I'm just missing something really silly?
function checkAlNum($whichField)
{
if (preg_match('/^[a-z0-9]{6,15}$/i', $_POST[$whichField])) {
return true;
}
else {
$message = '<p>Username and password can only be numbers or letters, 6-15 characters long</p>';
return user_error($message);
}
}
Without the ^ and $ anchors, your regex only checks whether there are alphanumerics anywhere in the field, not that the whole thing is alphanumeric. And changing + to {6,15} implements the length check here, so you can remove that extra check in your code.
I think the second if statement is incorrect. It should be like this:
if ( !( (!count(strlen($whichField) >= 6)) OR (!count(strlen($whichField) <= 15 )) ) ) {
// ... do something
}
This is due to De Morgan Rule which states
A AND B = !( !A OR !B )
In any case, I would not do my checks this way, strucurally you will end up with too many nested if statements that are hard to maintain and make your code look unpretty. Try avoiding nested conditions in your code.
Barmar's answer is the best. But if you want to keep your if statement to check string length, you need to remove the count() as you are already checking the length using strlen().
if ( (!(strlen($whichField) >= 6)) OR (!(strlen($whichField) <= 15 ))) {