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

  • Home
  • SEARCH
  • 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 7398999
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T03:57:00+00:00 2026-05-29T03:57:00+00:00

I need a php validator class that validates user inputs. I want it to

  • 0

I need a php validator class that validates user inputs.

I want it to be able to accept an assoc array of fields => values like:

array(
    "username" => "Alex",
    "email_address" => "@@#3423£alex@my.mail.com"
);

and then return an array of errors like this:

array(
    "username" => "",
    "email_address" => "Invalid Email Address"
);

But I’m really struggling on HOW the hell I’m going to do this!

I’ve read countless pages on PHP validators and read that the best way to do this is with the strategy pattern. But i dont know how??

Like… This is what I’ve got so far:

class Validator {

private
$_errors,
$_fields,

static private $_map = array (
    "firstname" => "name",
    "surname" => "name",
    "agency_name" => "name",
    "agency_office" => "name",
    "username" => "username",
    "email_address" => "email_address",
);
public function __construct( array $fields ) {
    $this->_fields = $fields;
}
public function validate() {
    foreach ( $this->_fields as $field => $value ) {
        if ( method_exists( __CLASS__, self::$_map[$field] ) ) {
            if ( in_array( $field, self::$_map ) ) {
                $this->{self::$_map[$field]}( $field, $value );
            }
        }
        else {
            die( " Unable to validate field $field" );
        }
    }
}
public function get_errors() {
    return $this->_errors;
}
private function name( $field, $value ) {
    if ( !preg_match( "/^[a-zA-Z]{2,50}$/", $value ) ) {
        $this->errors[$field] = "Invalid. Must be 2 to 50 alphanumerical characters";
    }
}
private function username( $field, $value ) {
    if ( !preg_match( "/^[a-zA-Z0-9_\-]{10,50}$/", $value ) ) {
        $this->errors[$field] = "Invalid. Must be 10 to 50 characters. Can contain digits, characters, _ (underscore) and - (hyphen)";
    }
}
private function password( $field, $value ) {
    if ( !preg_match( "/^[a-zA-Z0-9\.\-]{8,30}$/", $value ) ) {
        $this->_errors[$field] = "Invalid. Must be 8 to 30 characters. Can contain digits, characters, . (full stop) and - (hyphen)";
    }
}
private function email_address( $field, $value ) {
    if ( !filter_var( $value, FILTER_VALIDATE_EMAIL ) ) {
        $this->_errors[$field] = "Invalid Email Address";
    }
}
}

The problems with this is, it doesn’t even consider database connections for like, already registered usernames,

Also is doesn’t match passwords

I’ve just got coders block at the moment and its destroying me on the inside 🙁

Can anybody give a an explaination of the classes required and functions each class will need to do?

I really need the inputs and outputs to be in the format already explained though!

Thankyou Very Much Internet People!

  • 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-29T03:57:02+00:00Added an answer on May 29, 2026 at 3:57 am

    As a part of the my MVC I have solved the same problem. I could give you a listing, but in a few lines try to describe how.

    I got 3 base classes Form, Validator, Field, each of object of this classes configuring through one YAML file, structured somehow like this:

    name: // field name
      i18n:             [ ru, en ] // is the field i18n
      field:
        class:          Base // class to use for field
        options:        { specific_save: true } // options from available (defined in class)
        attributes:     { } // attributes, for HTML rendering
      validator:
        class:          String // Class to validate with
        options:        { required: true, max: 100 } // options for validator
    

    So, lets start with Form, when object is constructing the form takes the YAML file described above, and due to that configuration creates fields. Something like this:

    // Imlement this function to configure form;
    foreach ($this->_config as $f => $c)
    {
        $class = '\\Lighty\\Form\\Field\\' . (isset($c['field']['class']) && $c['field']['class'] ? $c['field']['class'] : 'Base');
        $o = isset($c['field']['options']) && is_array($c['field']['options']) ? $c['field']['options'] : array();
        $a = isset($c['field']['attributes']) && is_array($c['field']['attributes']) ? $c['field']['attributes'] : array();
        $field = new $class($this, $o, $a);
        $field->setName($f);
    
        $class = '\\Lighty\\Form\\Validator\\' . (isset($c['validator']['class']) && $c['validator']['class'] ? $c['validator']['class'] : 'Base');
        $o = isset($c['validator']['options']) && is_array($c['validator']['options']) ? $c['validator']['options'] : array();
        $m = isset($c['validator']['messages']) && is_array($c['validator']['messages']) ? $c['validator']['messages'] : array();
        $field->setValidator($validator = new $class($field, $o, $m));
    
        if (isset($this->_options['default'][$f]))
        {
            $field->setValue($this->_options['default'][$f]);
        }
    
        if (isset($c['i18n']))
        {
            if (is_array($c['i18n']))
            {
                $field->setCultures($c['i18n']);
            }
            $field->setI18n((bool) $c['i18n']);
        }
    
        $this->addField($field);
    

    So, now we have form with fields and validator for each field, then to validate I use this mechanism:

    Form goes through each field, calling validate() method,
    Field (got the binded value) call validate($value) method of binded Validator, passing the stored value. Inside this method Validator calls the validateOption() method, in which there is a simple switch for each options, for example:

    switch ($o)
    {
        case 'required':
            $valid = $state && trim($value) != '' || !$state;
            break;
        default:
            return \warning(sprintf('Undefined validator option "%s" in %s validator class', $o, get_class($this->getField()->getValidator())), null);
    }
    

    Here you can see validating on required option. If I need more validators, I extend class of the Base validator, defined few more options, and redefine validateOption(), where in default statement of the option’s switch put parent::validateOption(). So specified options validates in new class, and old one in base validator Class.

    If there any questions… You’re welcome.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need a regex or a function in PHP that will validate a string
I need a php code and sql code that will let someone upload an
I need a PHP Regex that can parse .strings files. In particular, it needs
I need some PHP classes that deal with image processing in a good manner.
I have a Rails application that uses ActiveRecordStore for sessions. I need a PHP
I am looking for a form class that: Is standalone/doesnt need a framework to
First thing: I know that there is interface to W3C validator: http://pear.php.net/package/Services_W3C_HTMLValidator/ But I
I am looking for free/opensource php form email script/class. The main requirement is that
I need help understanding the logic to deal with validating user inputs. my current
I made a Validator that receives a class instance and a function name and

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.