Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 793535
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T22:10:07+00:00 2026-05-14T22:10:07+00:00

What’s an effective way to handle data validation, say, from a form submission? Originally

  • 0

What’s an effective way to handle data validation, say, from a form submission?

Originally I had a bunch of if statements that checked each value and collected invalid values in an array for later retrieval (and listing).

// Store errors here
$errors = array();

// Hypothetical check if a string is alphanumeric
if (!preg_match('/^[a-z\d]+$/i', $fieldvalue))
{
    $errors[$fieldname] = 'Please only use letters and numbers for your street address';
}

// etc...

What I did next was create a class that handles various data validation scenarios and store the results in an internal array. After data validation was complete I would check to see if any errors occurred and handle accordingly:

class Validation
{
    private $errorList = array();

    public function isAlphaNumeric($string, $field, $msg = '')
    {
        if (!preg_match('/^[a-z\d]+$/i', $string))
        {
            $this->errorList[$field] = $msg;
        }
    }

    // more methods here

    public function creditCard($cardNumber, $field, $msg = '')
    {
        // Validate credit card number
    }

    // more methods here

    public function hasErrors()
    {
        return count($this->errorList);
    }
}

/* Client code */

$validate = new Validation();
$validate->isAlphaNumeric($fieldvalue1, $fieldname1, 'Please only use letters and numbers for your street address');
$validate->creditCard($fieldvalue2, $fieldname2, 'Please enter a valid credit card number');

if ($validate->hasErrors())
{
    // Handle as appropriate
}

Naturally it didn’t take long before this class became bloated with the virtually unlimited types of data to be validated. What I’m doing now is using decorators to separate the different types of data into their own classes and call them only when needed leaving generic validations (i.e. isAlphaNumeric()) in the base class:

class Validation
{
    private $errorList = array();

    public function isAlphaNumeric($string, $field, $msg = '')
    {
        if (!preg_match('/^[a-z\d]+$/i', $string))
        {
            $this->errorList[$field] = $msg;
        }
    }

    // more generic methods here

    public function setError($field, $msg = '')
    {
        $this->errorList[$field] = $msg;
    }

    public function hasErrors()
    {
        return count($this->errorList);
    }
}

class ValidationCreditCard
{
    protected $validate;

    public function __construct(Validation $validate)
    {
        $this->validate = $validate;
    }

    public function creditCard($cardNumber, $field, $msg = '')
    {
        // Do validation
        // ...
        // if there is an error
        $this->validate->setError($field, $msg);
    }

    // more methods here
}

/* Client code */

$validate = new Validation();
$validate->isAlphaNumeric($fieldvalue, $fieldname, 'Please only use letters and numbers for your street address');

$validateCC = new ValidationCreditCard($validate);
$validateCC->creditCard($fieldvalue2, $fieldname2, 'Please enter a valid credit card number');

if ($validate->hasErrors())
{
    // Handle as appropriate
}

Am I on the right track? Or did I just complicate data validation more then I needed to?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T22:10:08+00:00Added an answer on May 14, 2026 at 10:10 pm

    If anything, you’re not validating enough. For reading data in $_POST and $_GET you need at least:

    • To check whether it exists (array_key_exists)
    • To check whether it’s an array or not
    • If expecting UTF-8, check whether it’s valid UTF-8 (preg_match with the ‘u’ modifier is an option)
    • Then do validation specific to the type of field

    By the way, the current hip way to do validation and sanitization in PHP is to use filters. In your specific case, here is an example:

    <?php
    $data = array(
        "arg1good" => "sdgdf790",
        "arg1bad"  => "sdgdf7/90",
        "arg1bad2" => array("sdgdf90", "sfdssf"),
        "arg2good" => "4567576456",
        "arg2bad"  => "45675764561",
    );
    
    $validateCredCard = function ($cc) {
        if (preg_match('/^\\d{10}$/', $cc))
            return $cc;
        else
            return false;
    };
    
    $arg1filt = array('filter'  => FILTER_VALIDATE_REGEXP,
                      'flags'   => FILTER_REQUIRE_SCALAR,
                      'options' => array('regexp' => '/^[a-z\d]+$/i'),
                      );
    $arg2filt = array('filter'  => FILTER_CALLBACK,
                      'flags'   => FILTER_REQUIRE_SCALAR,
                      'options' => $validateCredCard,
                      );
    $args = array(
        "arg1good" => $arg1filt,
        "arg1bad"  => $arg1filt,
        "arg1bad2" => $arg1filt,
        "arg2good" => $arg2filt,
        "arg2bad"  => $arg2filt,
    );
    
    var_dump(filter_var_array($data, $args));
    

    gives:

    array(5) {
      ["arg1good"]=>
      string(8) "sdgdf790"
      ["arg1bad"]=>
      bool(false)
      ["arg1bad2"]=>
      bool(false)
      ["arg2good"]=>
      string(10) "4567576456"
      ["arg2bad"]=>
      bool(false)
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have a text area in my form which accepts all possible characters from
I have a bunch of posts stored in text files formatted in yaml/textile (from
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I am doing a simple coin flipping experiment for class that involves flipping a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.