I am not sure if this question has been answered in round about ways through other questions but...
I am creating a web page for my job which has multiple entry fields (all of which have the same validation code). The following is a small section of my php code:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["bottomair"])) {
$bottomairerror = "Maketable bottom air temp is required";
} else {
$bottomair = test_input($_POST["bottomair"]);
if (!filter_var($bottomair, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$coldmin, "max_range"=>$coldmax)))) {
$bottomairerror = $errormsg;
}
}
if (empty($_POST["topair"])) {
$topairerror = "Maketable top air temp is required";
} else {
$topair = test_input($_POST["topair"]);
if (!filter_var($topair, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$coldmin, "max_range"=>$coldmax)))) {
$topairerror = $errormsg;
}
}
if (empty($_POST["meat"])) {
$meaterror = "Maketable meat temp is required";
} else {
$meat = test_input($_POST["meat"]);
if (!filter_var($meat, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$coldmin, "max_range"=>$coldmax)))) {
$meaterror = $errormsg;
}
}
if (empty($_POST["cheese"])) {
$cheeseerror = "Maketable cheese temp is required";
} else {
$cheese = test_input($_POST["cheese"]);
if (!filter_var($cheese, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$coldmin, "max_range"=>$coldmax)))) {
$cheeseerror = $errormsg;
}
}
if (empty($_POST["walkin"])) {
$walkinerror = "Walk-In temp is required";
} else {
$walkin = test_input($_POST["walkin"]);
if (!filter_var($walkin, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$coldmin, "max_range"=>$coldmax)))) {
$walkinerror = $errormsg;
}
}
if (empty($_POST["refrig1"])) {
$refrig1error = "Refrigerator #1 temp is required";
} else {
$refrig1 = test_input($_POST["refrig1"]);
if (!filter_var($refrig1, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$coldmin, "max_range"=>$coldmax)))) {
$refrig1error = $errormsg;
}
}
if (empty($_POST["refrig2"])) {
$refrig2error = "Refrigerator #2 temp is required";
} else {
$refrig2 = test_input($_POST["refrig2"]);
if (!filter_var($refrig2, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$coldmin, "max_range"=>$coldmax)))) {
$refrig2error = $errormsg;
}
}
if (empty($_POST["refrig3"])) {
$refrig3error = "Refrigerator #3 temp is required";
} else {
$refrig3 = test_input($_POST["refrig3"]);
if (!filter_var($refrig3, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$coldmin, "max_range"=>$coldmax)))) {
$refrig3error = $errormsg;
}
}
}
Is there a function which I can use to "tidy up" my php code so that I do not have as many lines to debug when things go sideways with the coding?
I think you only have three options here:
Write perfect code so that your code never goes sideways (highly unlikely for any developer :)
Change from an if structure to a switch structure
Evolve your debugging procedure/tools to make debugging less painful in general.
Create an array with the names of the required fields as a key, and an error message as a value. Then loop through this array. Use the keys in the $_POST superglobal to see if it's been set. If it's not set, throw the error message you defined as the value. Something along the lines of:
$required_parameters = array(
"bottomair" => "Maketable bottom air temp is required",
"topair" => "Maketable top air temp is required",
// etc
);
$errorslist = array();
foreach($required_parameters as $key => $error)
{
if(empty($_POST[$key]))
{
$errorslist[] = $error; // append to list
}
else
{
$test = test_input($_POST[$key]);
if (!filter_var($test, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$coldmin, "max_range"=>$coldmax))))
{
$errorslist[] = $errormsg; // <-- I don't know where you define errormsg, though
}
}
}
You can then loop through the $errorslist array as well to display all errors in a list.
Related
I've created a registering form, and I'd like to validate user input, for security purposes.
I've created some functions, shown below.
I am just unsure on how to implement them correctly. Do I nest if statements? Do I just keep it like I have it now?
How do I stop my script when something isn't right? To prevent an insert from even being tried when something isn't right.
Any help is greatly appreciated.
function validateLength($stringToValidate, $minimumLength) {
if(strlen($stringToValidate) < $minimumLength) {
return [
'error' => 'Minimum length is 8 charachters',
'class' => 'alert alert-danger',
];
} else {
return true;
}
}
function validateEmail($emailToVerify) {
if(filter_var($emailToVerify, FILTER_VALIDATE_EMAIL)) {
return true
} else {
return [
'error' => '<strong>Error:</strong> That is not a valid email address',
'class' => 'alert alert-danger'
];
}
}
function formIsFilledIn(array $formInputs = []) {
foreach ($formInput as $inputField) {
if(empty($inputField)) {
return [
'error' => '<strong>Error: </strong> Fill in all fields.',
'class' => 'alert alert-danger',
];
}
}
return null;
}
Now, I'm using every function like so.
$formErrors = formIsFilledIn($_POST);
if($formErrors !== null) {
// Something is not filled in
}
$formErrors = validateLength($_POST['username'], 8);
if($formErrors !== true) {
// Username doesn't have enough characters
}
$formErrors = validateLength($_POST['password'], 8);
if($formErrors !== true) {
// Password doesn't have enough characters
}
For completeness, this is the insert part (it works properly)
$stmt = $connect->prepare('INSERT INTO `users` (user_name, user_password, user_email, user_perms, user_created_at) VALUES (?, ?, ?, ?, ?)');
if($stmt) {
$username = $_POST['username'];
$password = hashPassword($_POST['password']);
$email = $_POST['email'];
$date = date('Y-m-d H:i:s');
$perms = "Gebruiker";
$stmt->bind_param('sssss', $username, $password, $email, $perms, $date);
if($stmt->execute()) {
$err = "<strong>Success: </strong> The account has been created";
$class = "alert alert-success";
} else {
$err = "<strong>Error:</strong> Something went wrong";
$class = "alert alert-danger";
}
}
You could indeed chain the if's together using elseif. I would however suggest some changes to the functions. Instead of letting them validate and return an array containing some errors, you'd need to only let them validate and return either true or false
It would look somewhat like this:
function validateLength($stringToValidate, $minimumLength) {
if(strlen($stringToValidate) < $minimumLength) {
return false;
} else {
return true;
}
}
function validateEmail($emailToVerify) {
if(filter_var($emailToVerify, FILTER_VALIDATE_EMAIL)) {
return true;
} else {
return false;
}
}
function formIsFilledIn(array $formInputs = []) {
foreach ($formInputs as $inputField) {
if(empty($inputField)) {
return false;
}
}
return true;
}
This means that you can do the following:
if(!formIsFilledIn($_POST)) {
$error = [
'error' => '<strong>Error: </strong> Fill in all fields.',
'class' => 'alert alert-danger',
];
} elseif(!validateLength($_POST['username'], 8) || !validateLength($_POST['password'], 8)) {
$error = [
'error' => 'Minimum length is 8 charachters',
'class' => 'alert alert-danger',
];
}
elseif(!validateEmail($_POST['email'])) {
$error = [
'error' => '<strong>Error:</strong> That is not a valid email address',
'class' => 'alert alert-danger'
];
}
else {
// now you can call a function that starts to insert stuff, everything has been validated
}
Of course, this would becomes longer the longer the form will get. An other option would be to iterate over the post and check if all fields have a valid length. When that is done you can check the email and all other special fields
Hello I am writing an php application and currently I'm stuck at a method that retrives flights from the database and applies diffrent filters to it. There are no problems when I initially load the page without any filters applied, all records from DB are loaded as expected. Then again everything as expected when I use "Departure Airport" or "Arrival Airport" filters along with "Bookable Only" filter.
It is whole of another story when you try to use "Bookable Only" filter on its own, it doesn't load any records from database. That's the same with "Aircraft" filter, doesn't work on its own and with "Bookable Only" filter but works when combined with both or either one of Airport filters + "Bookable Only" filter
Schedules_model.php
public function getFilteredSchedule($available, $departureICAO, $arrivalICAO, $specificAircraftId)
{
$this->db->select('*');
if($departureICAO != FALSE) {
$this->db->where('departureICAO', $departureICAO);
}
if($arrivalICAO != FALSE) {
$this->db->where('arrivalICAO', $arrivalICAO);
}
if($specificAircraftId != FALSE) {
$this->db->where('aircraftId', $specificAircraftId);
}
$schedules = $this->db->where('active', 1)
->order_by('id', 'asc')
->get('schedules')
->result_array();
$schedulesAvailable = array();
if($available === TRUE) {
echo 'work';
foreach($schedules as $key => $schedule) {
if($this->RebuildVA->mustBeAtDepartureAirport()) {
if($this->Aircrafts->isAtAirport($schedule['aircraftId'], $schedule['departureICAO'])) {
$schedulesAvailable[$key] = $schedule;
} else {
break;
}
} else {
$schedulesAvailable[$key] = $schedule;
}
if(!$this->RebuildVA->allowMultipleAircraftBookings()) {
if(!$this->Aircrafts->isBooked($schedule['aircraftId'])) {
$schedulesAvailable[$key] = $schedule;
} else {
break;
}
} else {
$schedulesAvailable[$key] = $schedule;
}
if(!$this->RebuildVA->allowMultiplePilotBookings()) {
if(!$this->Pilots->hasBookedFlight($this->session->userdata('pilotId'))) {
$schedulesAvailable[$key] = $schedule;
} else {
break;
}
} else {
$schedulesAvailable[$key] = $schedule;
}
}
} else {
$schedulesAvailable = $schedules;
}
return $schedulesAvailable;
}
schedules.php
public function search()
{
$this->data['pageTitle'] = 'Schedule Search';
$this->data['pageDisplayedTitle'] = 'Schedule Search';
$available = (bool) $this->input->post('available');
$this->data['schedules'] = $this->Schedules->getFilteredSchedule($available, $this->input->post('departureICAO'), $this->input->post('arrivalICAO'), $this->input->post('aircraftId'));
$airportsList = $this->Airports->getAllAirports(TRUE, TRUE); // Get set of all active airports
$aircraftsList = $this->Aircrafts->getAllAircrafts(TRUE, TRUE); // Get set of all active airports
// Prepare form inputs
$this->data['departureICAO'] = array(
'name' => 'departureICAO',
'id' => 'departureICAO',
'selected' => $this->input->post('departureICAO'),
'options' => $airportsList,
);
$this->data['arrivalICAO'] = array(
'name' => 'arrivalICAO',
'id' => 'arrivalICAO',
'selected' => $this->input->post('arrivalICAO'),
'options' => $airportsList,
);
$this->data['aircraftId'] = array(
'name' => 'aircraftId',
'id' => 'aircraftId',
'selected' => $this->input->post('aircraftId'),
'options' => $aircraftsList,
);
$this->data['available'] = array(
'name' => 'available',
'id' => 'available',
'checked' => set_checkbox('available', $this->input->post('available'), FALSE),
'value' => TRUE,
);
$this->load->view('schedules/scheduleSearch', $this->data);
}
I tried debugging everything and following the process step by step as well as trial and error method but none give expected effects. Any ideas?
By trial and error method I have found some kind of a work around that some how does the job. If anyone has any suggestions regarding it or how I could improve it, please feel free, as I am looking for performance in the app.
The required changes were in the Model:
public function getFilteredSchedule($available, $departureICAO, $arrivalICAO, $specificAircraftId)
{
$this->db->select('*');
if($departureICAO != FALSE) {
$this->db->where('departureICAO', $departureICAO);
}
if($arrivalICAO != FALSE) {
$this->db->where('arrivalICAO', $arrivalICAO);
}
if($specificAircraftId != FALSE) {
$this->db->where('aircraftId', $specificAircraftId);
}
$schedules = $this->db->where('active', 1)
->order_by('id', 'asc')
->get('schedules')
->result_array();
$schedulesAvailable = array();
// Check if any of the filters is required
if(!$this->RebuildVA->mustBeAtDepartureAirport() && $this->RebuildVA->allowMultipleAircraftBookings() && $this->RebuildVA->allowMultiplePilotBookings()) {
$schedulesAvailable = $schedules;
// Check if only bookable flights has been checked
} elseif($available === TRUE) {
foreach($schedules as $key => $schedule) {
// Allow multiple schedule bookings
// Check if the aircraft must be at departure airport
if($this->RebuildVA->mustBeAtDepartureAirport()) {
if($this->Aircrafts->isAtAirport($schedule['aircraftId'], $schedule['departureICAO'])) {
$schedulesAvailable[$key] = $schedule;
} else {
// Check if use of other aircraft of same type is allowed
if($this->RebuildVA->allowOtherAircraftUse()) {
if($this->Aircrafts->aircraftTypeAtAirport($schedule['aircraftId'], $schedule['departureICAO'])) {
$schedulesAvailable[$key] = $schedule;
} else {
unset($schedulesAvailable[$key]);
continue;
}
} else {
unset($schedulesAvailable[$key]);
continue;
}
}
} else {
if(isset($schedulesAvailable[$key])) {
$schedulesAvailable[$key] = $schedule;
}
}
// Check if there is a limit of only one booking at time per aircraft
if(!$this->RebuildVA->allowMultipleAircraftBookings()) {
if(!$this->Aircrafts->isBooked($schedule['aircraftId'])) {
$schedulesAvailable[$key] = $schedule;
} else {
unset($schedulesAvailable[$key]);
continue;
}
} else {
if(isset($schedulesAvailable[$key])) {
$schedulesAvailable[$key] = $schedule;
}
}
// Check if there is a limit of only one booking at time per pilot
if(!$this->RebuildVA->allowMultiplePilotBookings()) {
if(!$this->Pilots->hasBookedFlight($this->session->userdata('pilotId'))) {
$schedulesAvailable[$key] = $schedule;
} else {
unset($schedulesAvailable[$key]);
continue;
}
} else {
if(isset($schedulesAvailable[$key])) {
$schedulesAvailable[$key] = $schedule;
}
}
}
} else {
$schedulesAvailable = $schedules;
}
return $schedulesAvailable;
}
<?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
Im building an API which requires some mandatory parameters to be POSTed to it.There are about 15 mandatory parameters which should be passed to the api,I wanted to show relevant errors to the developer if there is any parameter missing like "Could not process ; email parameter is missing ".
I have already implemented the logic,but its not working well and seems to be very badly coded with excess codes.This is the current approach
if ($data['email'] AND array_key_exists('email', $data)) {
if (!validateEmail($data['email'])) {
$transaction_error = 'Invalid email';
}
} else {
$transaction_error = 'Parameter email is missing';
}
if (!($data['addr'] AND array_key_exists('addr', $data))) {
$transaction_error= 'Parameter addr is missing';
}
if (array_key_exists('show_shipping_addr', $data)) {
if (!verifyBinary($data['show_shipping_addr'])) {
$transaction_error = 'Invalid show_shipping_addr';
}
} else {
$transaction_error = 'Parameter show_shipping_addr is missing';
}
if (array_key_exists('authorize_user', $data)) {
if (!verifyBinary($data['authorize_user'])) {
$transaction_error = 'Invalid authorize_user';
}
} else {
$transaction_error = 'Parameter authorize_user is missing';
}
if ($data['mobileNo'] AND array_key_exists('mobileNo', $data)) {
if (!validateMobileNo($data['mobileNo'])) {
$transaction_error = 'Invalid mobileNo';
}
} else {
$transaction_error = 'Parameter mobileNo is missing';
}
if ($data['currency_code'] AND array_key_exists('currency_code', $data)) {
if (!validateCurrencyCode($data['currency_code'])) {
$transaction_error = 'Invalid currency_code';
}
} else {
$transaction_error = 'Parameter currency_code is missing';
}
if ($data['checksum_method'] AND array_key_exists('checksum_method', $data)) {
if (!validateChecksumMethod($data['checksum_method'])) {
$transaction_error = 'Invalid checksum_method';
}
} else {
$transaction_error = 'Parameter checksum_method is missing';
}
if ($data['zipcode'] AND array_key_exists('zipcode', $data)) {
if (!validateZipCode($data['zipcode'])) {
$transaction_error = 'Invalid zipcode';
}
} else {
$errors[$i++] = 'Parameter zipcode is missing';
}
if ($data['f_name'] AND array_key_exists('f_name', $data)) {
if (!validateAlphaString($data['f_name'])) {
$transaction_error = 'Invalid name';
}
} else {
$transaction_error = 'Parameter f_name is missing';
}
if ($data['state'] AND array_key_exists('state', $data)) {
if (!validateAlphaString($data['state'])) {
$transaction_error = 'Invalid state';
}
} else {
$transaction_error = 'Parameter state is missing';
}
if ($data['country'] AND array_key_exists('country', $data)) {
if (!validateAlphaString($data['country'])) {
$transaction_error = 'Invalid country';
}
} else {
$transaction_error = 'Parameter country is missing';
}
if ($data['city'] AND array_key_exists('city', $data)) {
if (!validateAlphaString($data['city'])) {
$transaction_error = 'Invalid city';
}
} else {
$transaction_error = 'Parameter city is missing';
}
/* Validation of mandatory parameters ends here */
/* Validation of optional parameters starts here
*shipping_email
*shipping_mobileNo
*shipping_zipcode
*l_name
*shipping_addr
*shipping_city
*shipping_state
*shipping_country
*surl
*furl
*rurl
*/
if (array_key_exists('l_name', $data)) {
if (!validateAlphaString($data['l_name'])) {
$transaction_error = 'Invalid l_name';
}
}
if (array_key_exists('shipping_addr', $data)) {
if (!$data['shipping_addr']) {
$transaction_error = 'Parameter shipping_addr is missing';
}
}
if (array_key_exists('shipping_mobileNo', $data)) {
if (!validateMobileNo($data['shipping_mobileNo'])) {
$transaction_error = 'Invalid shipping_mobileNo';
}
}
if (array_key_exists('shipping_city', $data)) {
if (!validateAlphaString($data['shipping_city'])) {
$transaction_error = 'Invalid shipping_city';
}
}
if (array_key_exists('shipping_state', $data)) {
if (!validateAlphaString($data['shipping_state'])) {
$transaction_error = 'Invalid shipping_state';
}
}
if (array_key_exists('shipping_country', $data)) {
if (!validateAlphaString($data['shipping_country'])) {
$transaction_error = 'Invalid shipping_country';
}
}
if (array_key_exists('shipping_zipcode', $data)) {
if (!validateZipCode($data['shipping_zipcode'])) {
$transaction_error = 'Invalid shipping_zipcode';
}
}
if(isset($api_error)) // IF there are API error pages are rendered
{
$api_error_array['api_error'] = $api_error;
$this->render_api_errors($api_error_array);
}
else if (isset($transaction_error)) { //If there are transactional errors,user is redirected back to mercahnt response url
$api_data = $this->paymentgateway->getAPIData($data['app_used'], $data['apikey']);
$data['response_url'] = $api_data['response_url'];
$data['transaction_errors'] = $transaction_error;
$this->paymentgateway->logApiRequest($data['app_used'], $transaction_error, 'Notice', $data['ip_address'], $data['ip_address_customer']);
$this->redirect_transactional_error($data);
} else {
$this->process($data); //Calls the process function when everything is done
}
I have got some set of mandatory fields and some set of non mandatory fields.The non mandatory fields if set need to be checked for their validity.
Please suggest a convienient way for validating post requests without making the code heavy.I have seen the following codes
if($_SERVER['REQUEST_METHOD'] != "POST")
die("Error: Wrong method");
$fields = array("f1", "f2", "f3", "f4");
$field_names = array("field1", "field2", "field3", "field4");
$length = count($fields);
$missing_input = array();
for($i = 0; $i < $length; $i++)
if(empty($_POST[$fields[$i]]))
$missing_input[] = $field_names[$i];
if(!empty($missing_input))
die("Error: " . implode(", ", $missing_input)");
from SO which makes sense.Can some suggest me a best practice of validating mandatory parameter in an API and showing relevant errors based on that?Instead of validating each paramters individually,can i make a single function whcih will check for the paramters and show the errors?
You can create one array of fields name which need to be mandatory / validated
$validate = array(
'username' => array('mandatory' => true, 'regex' => '/^[a-z0-9_-]{3,16}$/'),
'password' => array('mandatory' => true, 'regex' => null),
// Same like the above example you can create all validation
)
$missing_input = array();
foreach($_POST as $key => $val){
$mandatory = isset($validate[$key]) ? $validate[$key] : false;
if($mandatory && !trim($val)){
// Manage error here
$missing_input[] = $key;
}
// Same like above get the regex and validate the field here and manage the error
}
// Return / Print error array
if(!empty($missing_input))
die("Error: " . implode(", ", $missing_input)");
you can also define the min and max limit in the $validate array and inside the foreach loop validate accordingly, simple logic to validate asper your requirement.
$validate = array(
'username' => array('mandatory' => true, 'regex' => '/^[a-z0-9_-]{3,16}$/'),
'password' => array('mandatory' => true, 'regex' => null),
// Same like the above example you can create all validation
)
$missing_input = array();
$invalid_input = array();
foreach($_POST as $key => $val){
$mandatory = isset($validate[$key]['mandatory']) ? $validate[$key]['mandatory'] : false;
$regex = isset($validate[$key]['regex']) ? $validate[$key]['regex'] : null;
if($mandatory && !trim($val)){
// Manage error here
$missing_input[] = $key;
} else if($regex != null && trim($val)){
if(!preg_match($regex,$val)){
$invalid_input[] = $key;
}
}
}
// Return / Print error array
if(!empty($missing_input))
die("Missing Inputs: " . implode(", ", $missing_input). "Invalid Inputs" . implode(", ", $invalid_input));
$data = array('addr'=>'test','mobileNo'=>'test');//only for test
$dataMandatory = array('email'=>1,'addr'=>1,'mobileNo'=>1);//array of mandatory field
$transaction_error=array();//array to contain error
foreach($data as $key=>$value){
if (array_key_exists($key, $dataMandatory)) {
unset($dataMandatory[$key]);
if(!call_user_func('validate'.ucfirst($key), $value)){//i call valide method
$transaction_error[] = 'Invalid '.$key;
}
}
}
if(count($dataMandatory)!==0){
$transaction_error[] = 'Parameter missing : '.implode(',',array_flip ($dataMandatory));
}
Pros : only on array to change for add mandatory field, no duplicate code
Cons : u cant change function name (valideKey) and custom treatment
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
?>