logo
down
shadow

Trying to create a generalized function in PHP 5.2, error message not showing


Trying to create a generalized function in PHP 5.2, error message not showing

Content Index :

Trying to create a generalized function in PHP 5.2, error message not showing
Tag : php , By : SpittingCAML
Date : November 29 2020, 09:01 AM

will be helpful for those in need Further to my comment, here is what I meant by passing the variables as an array then looping over them, applying your patterns, and passing $errors by reference:
$patterns = array(
    "fname" => '/^[a-zA-Z]{2,15}$/',
    "lname" => '/^[a-zA-Z]{2,15}$/',
    "phone" => '/^(\(\d{3}\))(\d{3}\-)(\d{4})$/',
    "city" => '/^[a-zA-Z]{3,20}$/',
    "state" => '/^[a-zA-Z]{2}$/',
    );

$errors = array(
    "fname" => "Please enter your FIRST name between 2 and 15 letters.<br>",
    "lname" => "Please enter your LAST name between 2 and 15 letters.<br>",
    "phone" => "Please enter your phone number in (###)###-### format.<br>",
    "city" => "Please enter your city name between 3 and 20 letters.<br>",
    "state" => "Please enter your state's abbreviation (Example: CA).<br>",
    );

// Pass by ref--------------------------------vv
function validateFormInput($input, $patterns, &$errors)
    {
        $new    =   false;
        foreach($input as $key => $value) {
            if(preg_match($patterns[$key], $value, $match))
                unset($errors[$key]);
        }

        return (empty($errors));
    }

$valid  =   false;

if(isset($_POST['submit'])) {
    $inputs =   $_POST;
    unset($inputs['submit']);

    $valid  =   validateFormInput($inputs,$patterns,$errors);

    if(!empty($errors))
        echo implode("<br />",$errors);
}

if(!$valid) {
?>
<form method="post">
    <input type="text" name="fname" value="Name" />
    <input type="text" name="lname" value="LastName" />
    <input type="text" name="phone" value="123-123-1233" />
    <input type="text" name="city" value="Reno" />
    <input type="text" name="state" value="NsrV" />
    <input type="submit" name="submit" value="submit" />
</form>
<?php   }
define("ERRMODE",true);

function validateFormInput($input)
    {
        $errors =   false;

        foreach($input as $key => $value) {
            $pattern    =   patternList($key);
            if(!$pattern)
                continue;

            if(!preg_match($pattern, trim($value), $match)) {
                $errors[$key]   =   errorMsg($key);
            }
        }

        return $errors;
    }

function patternList($name = false)
    {
        $patterns = array(
            "fname" => '/^[a-zA-Z]{2,15}$/',
            "lname" => '/^[a-zA-Z]{2,15}$/',
            "phone" => '/^(\(\d{3}\))(\d{3}\-)(\d{4})$/',
            "city" => '/^[a-zA-Z]{3,20}$/',
            "state" => '/^[a-zA-Z]{2}$/',
            );

        return (isset($patterns[$name]))? $patterns[$name]:false;
    }

function errorMsg($name = false)
    {
        $errors = array(
            "fname" => "Please enter your FIRST name between 2 and 15 letters.",
            "lname" => "Please enter your LAST name between 2 and 15 letters.",
            "phone" => "Please enter your phone number in (###)###-### format.",
            "city" => "Please enter your city name between 3 and 20 letters.",
            "state" => "Please enter your state's abbreviation (Example: CA).",
            );

        return (isset($errors[$name]))? $errors[$name]:false;
    }

function printPre($val = false)
    {
        ob_start();
        echo "<pre>";
        print_r($_POST);
        echo "</pre>";
        $data = ob_get_contents();
        ob_end_clean();

        return $data;   
    }

if(isset($_POST['submit'])) {

    if(ERRMODE) { 
        echo printPre($_POST);
        echo printPre($_FILES); 
    }

    $errors         =   validateFormInput($_POST);
    $formValid      =   (empty($errors));

    $fname          =   htmlspecialchars($_POST['fname']);
    $lname          =   htmlspecialchars($_POST['lname']);
    $phone          =   htmlspecialchars($_POST['phone']);
    $city           =   htmlspecialchars($_POST['city']);
    $state          =   htmlspecialchars($_POST['state']);
    $mobile         =   preg_replace('/\D+/', '', $phone);
}
?><!DOCTYPE html>
<html>
<head>
<title>Lesson 7</title>
<meta charset="UTF-8">
<meta name="description" content="php">
<meta name="keywords" content="php">
<meta name="author" content="William Payne">
<link rel="stylesheet" type="text/css" href="xxxxxxxxxxxx">
</head>
<body>    
    <div class="formLayout">
<?php 
//form
  if (empty($formValid)) {
        if(!empty($errors))
            echo implode("<br />",$errors);
?>
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data">  
     <fieldset>
     <legend>Info</legend>
     <?php echo $error_text ?>
     <label>First Name:</label><input name="fname" type="text" value="<?php echo (!empty($fname))? $fname : ""; ?>"><br>
     <label>Last Name:</label><input name="lname" type="text" value="<?php echo (!empty($lname))? $lname : ""; ?>"><br>
     <label>Phone Number:</label><input name="phone" type="text" value="<?php echo (!empty($phone))? $phone : ""; ?>"><br>
     <label>City:</label><input name="city" type="text" value="<?php echo (!empty($city))? $city : ""; ?>"><br>
     <label>State:</label><input name="state" type="text" value="<?php echo (!empty($state))? $state : ""; ?>"><br>
     </fieldset>
     <input name="submit" id="submit" type="submit" value="submit"><br>
    </form> 
<?php
  } else {
?>       
        <p><strong><?php echo "$welcome_msg"; ?></strong></p>  
        <p><strong><?php echo "{$lname}, {$fname}";?></strong></p>
        <p><strong><?php echo "{$phone}"; ?></strong></p>
        <p><strong><?php echo "{$city}, {$state}"; ?></strong></p> 
<?php
  }
?>
     </div>
  </body>
</html> 

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Devise - Error message not showing up - redirects to update instead of create


Tag : ruby-on-rails , By : pttr
Date : March 29 2020, 07:55 AM
I wish did fix the issue. I don't like this, but it works. If anyone has a better way of doing this, please let me know. Thank you.
...
else
  resource.unregistered_advisor = true
  clean_up_passwords(resource)
  a = User.new(:email => resource.email, :name => resource.name, :confirmation_token => resource.confirmation_token)
  resource.errors.each do |key,value|
    a.errors[key] = value
  end
  self.resource = a
  respond_with_navigational(resource) { render_with_scope :new }
end
...

Create React App not showing error message with ErrorBoundary


Tag : reactjs , By : alchemist
Date : March 29 2020, 07:55 AM
I wish this helpful for you As per this issue on github,

Firebase Cloud Function not showing error message


Tag : firebase , By : Thomas Gueze
Date : March 29 2020, 07:55 AM
hope this fix your issue So, after toggling around, I found out this error occurs when Firebase is capping your funciton execution time, so I solved it by upgrading my plan to Blaze

PHP $_GET function, error message not showing


Tag : php , By : Moe Skeeto
Date : March 29 2020, 07:55 AM

Laravel Internal Error Page is showing exception message instead generic error message


Tag : laravel , By : Marc
Date : September 28 2020, 09:00 PM
fixed the issue. Will look into that further I have an laravel 5.7 application that when I deactivate debug mode the internal server error page keeps showing the exception message instead of the generic message "Whoops, something went wrong on our servers!". , File .env
APP_DEBUG=false
'debug' => env('APP_DEBUG', false),
php artisan config:cache
Related Posts Related QUESTIONS :
  • How to do mysql LEFT JOIN for Google multiple line chart (php, mysql)?
  • Find the two longest strings separated by dash in PHP
  • Cannot access private property with Set method in Symfony
  • How to compare 2 array of PHP objects then fill in empty string if data not match?
  • strtotime gives back false result to strings in an array
  • How to create Url that contain name and id laravel
  • Codeigniter: Models not working with an error: Undefined property: CI_Loader
  • How to use + or - operators as parameters in Doctrine prepared SQL statement?
  • How to run scrapy with url parameters from php on linux debian
  • Preg matching imgur.com links
  • Php - Code comparing value of database to the value send by android app
  • Laravel pagination object in javascript
  • Error in validating message of no votes PHP
  • Symfony site on Azure with ClearDB connection
  • Woocommerce upsell with checkboxes
  • How to login/logout with Hybridauth 3?
  • Convert INT number in PHP
  • php/mysql. selecting 2 common fields in 2 tables
  • Expand an string based on values in an array in PHP
  • When you absolutely have to manually escape SQL in CakePHP 3.4.7
  • Htaccess redirecting wrong page
  • Laravel Optional WHERE clause
  • PHP unpack overlfow variable memory limit
  • How to check the URL's structure using PHP preg_match?
  • PHP preg_replace - text will not be recognized
  • Show image from other domain without showing the domain name - PHP
  • How to run and watch local server at the same time?
  • Access form request from Observer laravel
  • single quote problem with preg_replace_callback
  • How to Create A Unique URL for each product enquiry form for Google Analytics Tracking
  • Laravel email configuration: what am I missing?
  • Assign indexed array values to multidimensional array?
  • Custom WordPress stylesheet not loading
  • Data attribute only returning first value
  • How to list all roles with Permissions,in spatie permission Package?
  • How to achieve this number pattern with n input
  • How to iterate array inside array data in laravel ,output are given below
  • To get output of movie with its genre
  • Extracting some data from a JS object literal string in PHP using Regex
  • axios and vuex are deleting wrong index in array
  • Setting empty CURLOPT_POSTFIELDS
  • Laravel 5.8 use subdomain as API endpoint beside domain.com/api
  • Error while add data in database SQL Server 2016
  • Does PhpStorm allow to skip PHPDoc tags when type hints is declared?
  • html classes are changed to Attributes
  • Using json to import multidimensional data
  • passing data from the view to the controller, where the data comes from another controller
  • How to extract integer and decimal numbers in PHP string correctly?
  • Parsing Sub-Object from an XML Feed with objects
  • Getting error "Unknown column 'text' in 'field list'"
  • How to properly get onedrive access token via php and curl
  • How to add spell check to a php function
  • Is it posible to create css rules with php?
  • Pretty URL with $_GET method
  • Wordpress always load same page - index.php
  • Find value in array and return with new from different array
  • PHP multiple file upload with different keys
  • Can't modify times one a time without weird errors
  • Get size of scraped image with domcrawler (Goutte)
  • Laravel - Ordering a collection of models
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com