PHP: Validation of US Phone numbers - php

I am currently working with validation of US phone numbers. The issue is that code below is always echoing after a valid or invalid input Please enter a valid phone number . My basic logic of my code is that I am checking with the preg_match to see if there is match for a valid number. Example
How can I fix this or is there a better way to validate phone numbers?
Also, Is there away to echo the number formatted like this: (123)456-7890?
PHP:
if (isset($_POST['phone'])) {
if(preg_match('/^(\({1}\d{3}\){1}|\d{3})(\s|-|.)\d{3}(\s|-|.)\d{4}$/',$phone)) {
echo ('<div id="phone_input"><span id="resultval">'.$phone.'</span></div>');
}
else {
echo '<div id="phone_input"><span id="resultval">Please enter a valid phone number</span></div>';
}
}

Try This
<?php
class Validation {
public $default_filters = array(
'phone' => array(
'regex'=>'/^\(?(\d{3})\)?[-\. ]?(\d{3})[-\. ]?(\d{4})$/',
'message' => 'is not a valid US phone number format.'
)
);
public $filter_list = array();
function Validation($filters=false) {
if(is_array($filters)) {
$this->filters = $filters;
} else {
$this->filters = array();
}
}
function validate($filter,$value) {
if(in_array($filter,$this->filters)) {
if(in_array('default_filter',$this->filters[$filter])) {
$f = $this->default_filters[$this->filters[$filter]['default_filter']];
if(in_array('message',$this->filters[$filter])) {
$f['message'] = $this->filters[$filter]['message'];
}
} else {
$f = $this->filters[$filter];
}
} else {
$f = $this->default_filters[$filter];
}
if(!preg_match($f['regex'],$value)) {
$ret = array();
$ret[$filter] = $f['message'];
return $ret;
}
return true;
}
}
//example usage
$validation = new Validation();
echo nl2br(print_r($validation->validate('phone','555-555-1212'),true));
echo nl2br(print_r($validation->validate('phone','(555)-555-1212'),true));
echo nl2br(print_r($validation->validate('phone','555 555 1212'),true));
echo nl2br(print_r($validation->validate('phone','555.555.1212'),true));
echo nl2br(print_r($validation->validate('phone','(555).555.1212'),true));
echo nl2br(print_r($validation->validate('phone','(555)---555.1212'),true));//will not match
?>

Related

I want to display results outside of the function

I want to display results outside of the function
By sending the discount value outside the function
<?php
function product_discount($price)
{
if($price<5000)
{
$dis=$price*5/100;
}
else
{
$dis=$price*10/100;
}
$total=$price-$dis;
echo "ส่วนลดที่ได้::". $dis."บาท"."</br>";
echo "ราคาสุทธิ::". $total."บาท"."</br>";
}
$price1=product_discount(1000);
$price2=product_discount(5000);
?>
<?php
function product_discount($price)
{
if($price<5000)
{
$dis=$price*5/100;
}
else
{
$dis=$price*10/100;
}
return $dis;
}
$price = 5000;
$discount = product_discount($price);
$total = $price-$discount;
echo "ส่วนลดที่ได้::". $discount."บาท"."</br>";
echo "ราคาสุทธิ::". $total."บาท"."</br>";
?>
A function can only return 1 variable.
If you want to return multiple values ​​from a function, you can use an array.
function product_discount($price):array
{
if($price<5000)
{
$dis=$price*5/100;
}
else
{
$dis=$price*10/100;
}
$total=$price-$dis;
return ['dis' => $dis, 'total' => $total];
}
$arr = product_discount(1000);
echo "dis:". $arr['dis']."</br>";
echo "total:". $arr['total']."</br>";
// alternatively
$price2 = product_discount(5000)['total'];

PHP get link from txtfile, unset this link inside the array and get random array value

I'm trying to load a website url from a textfile, then unset this string from an array and pick a random website from the array.
But once I try to access the array from my function the array would return NULL, does someone know where my mistake is located at?
My current code looks like the following:
<?php
$activeFile = 'activeSite.txt';
$sites = array(
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
);
function getActiveSite($file)
{
$activeSite = file_get_contents($file, true);
return $activeSite;
}
function unsetActiveSite($activeSite)
{
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}
function updateActiveSite($activeFile)
{
$activeWebsite = getActiveSite($activeFile);
if(!empty($activeWebsite))
{
$unsetActive = unsetActiveSite($activeWebsite);
if($unsetActive == true)
{
$randomSite = $sites[array_rand($sites)];
return $randomSite;
}
else
{
echo 'Could not unset the active website.';
}
}
else
{
echo $activeWebsite . ' did not contain any active website.';
}
}
$result = updateActiveSite($activeFile);
echo $result;
?>
$sites is not avaliable in unsetActiveSite function you need to create a function called "getSites" which return the $sites array and use it in unsetActiveSite
function getSites(){
$sites = [
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
];
return $sites;
}
function unsetActiveSite($activeSite)
{
$sites = getSites();
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}

Get only a specified name of email

I have a problem with preg_math. So I have this methode :
public function filterUsers($a_users){
$a_authorizedEmail = array(
'#test.com',
'#test1.com'
);
$a_response = array();
foreach ($a_users as $user) {
if(false !== $email_user = EmailRepository::getEmail($user['id'])){
foreach($a_authorizedEmail as $email){
echo $email_user;
if(preg_match($email, $email_user)){
$a_response[]= $user;
}
}
}
}
return $a_response;
}
The array with $a_users : I have a user with email hcost#test.com. But in the return the array is empty. Probably I doen't made a correct verification. Please help me
Do this:
public function filterUsers($a_users){
$a_authorizedEmail = array(
'#test.com',
'#test1.com'
);
$pattern = "/".implode("|",$a_authorizedEmail)."$/"; //Note the "/" start and end delimiter as well as the $ that indicates end of line
$a_response = array();
foreach ($a_users as $user) {
$email_user = EmailRepository::getEmail($user['id']);
if(false !== $email_user){
echo $email_user;
if(preg_match($pattern, $email_user)){
$a_response[]= $user;
}
}
}
return $a_response;
}

Returning from parent function on checking the field values from seperate class

<?php
class CustomerLocation{
public function checkPhone($phone) {
if(isset($phone) && (strlen($phone) == 10 || strlen($phone) == 12))
{
return $phone;
}
else
{
$aResponse = array(
"error" => "400",
"message" => array(
"code" => "Invalid_phone",
"dev_msg" => "The phone must be at least 10 characters.",
"user_msg" => "Please enter valid phone number."
),
);
return $aResponse;
}
}
}
class test {
public function test()
{
$loc = new CustomerLocation();
$query = array("phone" => $loc->checkPhone('123456'));
// some more code be executed
}
}
I want to return from the test function with the response message written in checkPhone method of CustomerLocation class if the phone number does not match the specific condition. But the problem is that I want to check the field of the array which is either by post or request method. How to go about any help will be grateful. Thanks.
Check this,
<?php
class CustomerLocation{
public function checkPhone($phone = NULL) {
if(isset($phone) && (strlen($phone) == 10 || strlen($phone) == 12))
{
return $phone;
}
else
{
$aResponse = array(
"error" => "400",
"message" => array(
"code" => "Invalid_phone",
"dev_msg" => "The phone must be at least 10 characters.",
"user_msg" => "Please enter valid phone number."
),
);
return $aResponse;
}
}
}
class test {
public function testnew($phone1)
{
$loc = new CustomerLocation();
$checkphone = $loc->checkPhone($phone1);
$error = isset($checkphone['error']) ? $checkphone['error'] : '';
if($error == 400){
$query = array("phone" => $checkphone);
return $query;
}
else{
// do some thing
}
}
}
echo "<pre>";
$test = new test();
$phone1 = '0123456789';//$_POST['phone'];
$output = $test->testnew($phone1);
print_r($output);
May be solve your problem

read more function with codeigniter

i am trying to create a readmore function in codeigniter where the readmore link will be linked to a controller which would show all the data about that particular id....i am kind of confused on how to go about it... i tried...
<?php
$research_detail_url = site_url()."/research/research_details";
//echo json_encode($research)
if($research)
{
foreach ($research as $_research) {
$author = $_research->author;
$content = $_research->content;
$dsubmitted = $_research->dsubmitted;
echo "<div class='menu-collapse'> <h5>$author</h5>";
echo "<p>";
echo "<span class='support_text'>$content <span><br />";
echo "<span class='support_text'>$dsubmitted <span><br />";
echo "<a href='$research_detail_url' target='_blank' style='text-decoration:underline; color:#0088cc;'>
read more » </a>";
echo "</p> </div>";
}
}
?>
but i seem not be getting any results...i need help...
and this is my controller function.....
public function research_details($id='')
{
if(!$id)
{
echo "Project Id required";
return;
}
$_result = $this->projects_model->get_project($id);
if($_result)
{// success in fetching data hurray
$result['projects'] = $_result;
$users_ids = $this->users_model->get_user_ids(); //return available user id's
$groups_ids = $this->groups_model->get_group_ids(); //return available group id's
//echo json_encode($users_ids);
//echo json_encode($groups_ids);
$group_record = $this->map_names_to_ids($users_ids , $groups_ids );
$result['group_record'] = $group_record;
//load the view
$this->load->view('__includes__/header');
$this->load->view('__includes__/boostrap_responsive');
$this->load->view('projects/project_panel', $result);
$this->load->view('__includes__/footer_scripts');
$this->load->view('__includes__/wijmo_file_jquery');
$this->load->view('__includes__/footer');
}
else
{
exit("An Error occured in fetching the requested project");
}
}
and this is my model.....
<?php
class research_model extends CI_Model {
function add()
{
$this->db->insert('research',$_POST);
if($this->db->_error_number())
{
return $this->db->_error_number();
}
}
function update($article_id, $data_fields = NULL){
if($data_fields == NULL)
{
$this->db->where("article_id =".$article_id);
$this->db->update('research',$_POST);
}
else
{
$this->db->where("article_id =".$article_id);
$this->db->update('research',$data_fields);
}
$is_error = $this->db->_error_number();
if($is_error){
echo $is_error;
}
return TRUE;
}
function delete($id){
$this->db->where("article_id =".$id);
return $this->db->delete('research');
}
//return the research with this id
function get_research($id){
$this->db->where("article_id =".$id);
$query = $this->db->get('research');
if ($query->num_rows() > 0){
return $query->row_array();
}
else
echo $this->db->_error_message();
return FALSE;
}
//return the available research in the table
function get_research_all(){
$query = $this->db->get('research');
if ($query->num_rows() > 0)
{
foreach($query->result() as $row)
{
$result[] = $row;
}
return $result;
}
}
}
and my entire controller.....
<?php
class Research extends Public_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('research_model');
}
function index()
{
if($this->ion_auth->is_admin())
{
$result = $this->research_model->get_research_all();
$data = array(
'main_content' => 'research/index',
'research' => $result
);
$this->load->view("loader", $data);
}
else
{
redirect('home');
}
}//END INDEX
// public view
function current()
{
$result = $this->research_model->get_research_all();
$data = array('research' => $result);
$this->load->view('__includes__/header');
$this->load->view('__includes__/navbar');
$this->load->view('research/current', $data);
$this->load->view('__includes__/footer');
}
function add()
{
if($this->ion_auth->is_admin())
{
$this->load->view("loader",array('main_content'=>"research/add_research"));
}
}//END ADD
function edit($id='')
{
if(! $id)
{
echo "research Id required";
return;
}
$result = $this->research_model->get_research($id);
if( ! $result)
{
echo "Nothing to edit";
return;
}
$result['main_content'] = "research/add_research";
$this->load->view("loader",$result);
}//END EDIT
function delete($id='')
{
if(! $id)
{
echo "Id required";
return;
}
$this->research_model->delete($id);
$this->get_research();
}//END DELETE
function submit($id='')
{
//validate form [perform validation server-side to make sure of fields]
$this->load->library('form_validation');
$this->form_validation->set_rules('author', 'Author', 'trim|required|min_length[4]');
if ($this->form_validation->run() == FALSE){
//ajax data array
$data = array(
'server_validation' => validation_errors()
);
echo str_replace('\\/', '/', json_encode($data));
}
else{
if($id){
$result = $this->research_model->update($id);
$content = "article has been UPDATED successfully";
//$retArr["content"] = $content;
//echo json_encode($retArr);
}
else{
$result = $this->research_model->add();
$content = "article has been CREATED successfully";
//$retArr["content"] = $content;
//echo json_encode($retArr);
}
//if duplicate key
if($result == 1062){
//ajax data array
$data = array();
$data['is_valid'] = 0;
echo json_encode($data);
}else{
//ajax data array
$data = array(
'is_valid' => 1,
'content' => $content
);
echo json_encode($data);
}
}//end ELSE form valid
}//END SUBMIT
public function research_details($id='')
{
if(!$id)
{
echo "Project Id required";
return;
}
$_result = $this->research_model->get_research($id);
if($_result)
{// success in fetching data hurray
$result['article'] = $_result;
//load the view
$this->load->view('__includes__/header');
$this->load->view('__includes__/boostrap_responsive');
$this->load->view('research/research_details', $Aresult);
$this->load->view('__includes__/footer_scripts');
$this->load->view('__includes__/wijmo_file_jquery');
$this->load->view('__includes__/footer');
}
else
{
exit("An Error occured in fetching the requested project");
}
}//END EDIT
}
?>
my public controller
<?php
abstract class Public_Controller extends CI_Controller
{
public $about_data;
function __construct()
{
parent::__construct();
//Making This variable availale for the whole site
$this->load->model('about_model');
$this->load->model('captcha_model');
//get your data
$this->about_data = $this->about_model->get_abouts();
}
}
?>
I see a couple of problems:
In your view, you are not closing the span tags. You need
</span>
In your view, you are creating the link, but you are not
including an ID, which you need in your controller. What I mean by this is the following:
First,you create this $research_detail_url = site_url()."/research/research_details";.
Then echo "<a href='$research_detail_url' target='_blank' style=''>read more</a>";
As you can see, your URL does not have an ID when created. What you should do is something like this: $research_detail_url = site_url()."/research/research_details/31"; where 31 is a random ID. You need to come up with the right ID needed in order to pass it to your controller. Your controller is currently assigning a blank ID since none is being passed which is why you end up with a result of "Project Id required"

Categories