2
\$\begingroup\$

I have created a method that validates inputs based on a set of rules. If an error is found, it is put into an array which can later on be used to display the errors to the user.

Below is my code:

register.php

<?php
    require_once('core/init.php');

    if(input::inputExists()){
        $validate = new validate();
        $validate->checkInput($_POST, array(
            'username' => array(
                'formatted_name' => 'username',
                'required' => 'true',
                'min' => 4,
                'max' => 25,
                'unique' => 'users'
                ),
            'password' => array(
                'formatted_name' => 'password',
                'required' => 'true',
                'min' => 5
                ),
            'confirm_password' => array(
                'formatted_name' => 'password confirmation',
                'matches' => 'password',
                'required' => 'true'
                )
        ));
        if ($validate->validationPassed()) {
            // Register new member...
        } else {
            // Return Errors....
            print_r($validate->getErrors());
        }
    }

?>

<form method="POST" autocomplete="off">
    <div class="form-group">
        <label for="username">
            Username
        </label>
        <input type="text" name="username" id="username" />     
    </div>
    <div class="form-group">
        <label for="password">
            Password
        </label>
        <input type="password" name="password" id="password" />     
    </div>
    <div class="form-group">
        <label for="confirm_password">
            Confirm Password
        </label>
        <input type="password" name="confirm_password" id="confirm_password" />     
    </div>
    <div class="form-group">
        <input type="submit" />
    </div>
</form>

validate.class.php

<?php
class validate {
    private $errors;
    private $passed = 'false';

    // public function __construct(){}

    public function checkInput($data, $items = array()) {
        foreach($items as $item => $rules){
            foreach($rules as $rule => $rule_value){
                if ($rule != 'formatted_name'){
                    if ($rule === 'required' && empty($data[$item])){
                        $this->addError("{$rules['formatted_name']} is required.");
                    }
                    if ($rule === 'min' && strlen($data[$item]) < $rule_value){
                        $this->addError("{$rules['formatted_name']} must be at least {$rule_value} characters long.");
                    }
                    if ($rule === 'max' && strlen($data[$item]) > $rule_value){
                        $this->addError("{$rules['formatted_name']} can be a maximum of {$rule_value} characters long.");
                    }
                    if ($rule === 'matches' && $data[$item] != $rule_value){
                        $this->addError("{$rules['formatted_name']} does not match {$items[$rule_value]['formatted_name']}");
                    }
                }
            }

        }
    }

    private function addError($error){
        $this->errors[] = $error;
    }

    public function validationPassed(){
        return empty($this->errors);
    }

    public function getErrors(){
        return $this->errors;
    }
}

Any improvements, suggestions or advice you can give me?

\$\endgroup\$
2
\$\begingroup\$

Right well first off, I'd consider looking into a framework such as Symfony, Laravel, or some other PHP web framework if you want to get serious about doing web design. Right now there is a lot less baggage in rolling your own framework, and the learning curve can be a little steep on them, but once you understand how they work you can spend way less time writing the framework and much more time implementing the actual features you care about.

There are a lot of suggestions I'd consider making, but most involve using routing/middleware layers to accomplish what you are doing here in order to make that form validation logic re-usable in register.php. The logic itself looks fine, but as your needs grow more and more complex you're going to run into some huge pitfalls with the architecture, or lack thereof, you are currently using.

Either way, I'd consider taking a look at Symfony's Validator component. It does a lot of what you're trying to accomplish, but in a really concise and powerful way and eliminates the need to write all of that rule logic in validate.class.php.

From a stylistic point of view, class names should be uppercased and given a noun not a verb. So your class validate -> Validator. Furthermore, your file names should be named after the class they represent and upper cased so validate.class.php -> Validator.php.

That being said, the code is organized quite nicely and is easy to read. Keep up the good work!

\$\endgroup\$
  • \$\begingroup\$ Thanks for your answer. Regarding the framework, is that a good idea considering I have little knowledge of OOP? I'm not sure if I grasp the basics and am worried about missing out basic stuff by skipping to a framework that'll do it for me... \$\endgroup\$ – user21611060 Dec 14 '14 at 21:15
  • \$\begingroup\$ I think for a beginner it makes a lot of sense to use one actually. You'll be thrust straight into learning best practices, including OOP, from the start just by looking at their code/docs and building a system around it. I'd choose Laravel to start with personally. It may seem heavy but as you gain more experience you'll come to appreciate what it does for you. The other advantage is that you get to spend more time building cool features vs just trying to deal with basic web framework issues which have already been solved 1000 times over in PHP. \$\endgroup\$ – Derek Dowling Dec 14 '14 at 21:28
  • \$\begingroup\$ Ah I see. Okay, I'll take a look into Laraval since someone else also recommended it too. Thanks for your advice. \$\endgroup\$ – user21611060 Dec 14 '14 at 21:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.