S
S
Super Star2018-07-22 09:26:41
PHP
Super Star, 2018-07-22 09:26:41

How to add a validator?

Hello. I am writing my bike i.e. OOP, MVC framework. In the process, I decided not to write validations in the Account model, but to write a separate form validation class (in the end, I stole it from github =)).
The idea was that several validation methods could be applied to a field, let's say:

  1. The login field is required.
  2. Login must consist only of Russian letters.
  3. Login must be at least 3 characters long.

That is, for each incorrect action, one message would be thrown out, and not in a bunch or even in one line.
The code that I dug up is 100% working, but in the end I ran into the fact that I can’t check, say, email for existence in the database using this class ...
In a situation where the database already has such a password, email or login needs to be shown a message that there are, but I do not catch up with what needs to be done. Climbing into the database in this class makes no sense, because this is the task of the account model.
Is it possible to make such checks in this class? Can you tell me another class of about the same complexity.
In general, I will be glad to any practical advice.
Validator code:
<?php

namespace components\libs;

class Validator
{
    private $field_name;
    private $message;
    private $type_of_rule;
    private $param;
    private static $rules = [];
    private static $fields = [];
    private static $errors = [];


    public function __construct($field_name, $message, $type_of_rule, $param)
    {
        $this->field_name = $field_name;
        $this->message = $message;
        $this->type_of_rule = $type_of_rule;
        $this->param = $param;
    }

    public static function addRule($field_name, $message, $type_of_rule, $param = null)
    {
        self::$rules[] = new Validator($field_name, $message, $type_of_rule, $param);
    }

    public static function addEntries($fields) {
        foreach ($fields as $fieldname => $value) {
            self::$fields[$fieldname] = self::sanitize($value);
        }
    }

    public static function validate() {
        foreach (self::$rules as $rule) {
            self::testRule($rule);
        }
    }

    public static function sanitize($text)
    {
        $text = trim(strip_tags($text));

        if (get_magic_quotes_gpc()) {
            $text = stripslashes($text);
        }
        return $text;
    }
    
    public static function getErrors()
    {
        if (count(self::$errors)) {
            return self::$errors;
        }
        return false;
    }

    public static function longerThan($value, $min)
    {
        if (strlen($value) >= $min) {
            return true;
        }
        return false;
    }

    public static function shorterThan($value, $max)
    {
        if (strlen($value) <= $max) {
            return true;
        }
        return false;
    }

    public static function asEmail($value)
    {
        if (filter_var($value, FILTER_VALIDATE_EMAIL)) {
            return true;
        }
        return false;
    }

    public static function asPhoneNumber($value)
    {
        if (preg_match("/^\(?[0-9]{3}\)? *-? *[0-9]{3} *-? *[0-9]{4}$/", $value)) {
            return true;
        }
        return false;
    }

    private static function testRule($rule)
    {

        if (isset(self::$errors[$rule->field_name])) {
            return;
        }

        if (isset(self::$fields[$rule->field_name])) {
            $value = self::$fields[$rule->field_name];
        }
        else {
            $value = null;
        }

        switch ($rule->type_of_rule) {
            case 'required' :
                if (empty($value)) {
                    self::$errors[$rule->field_name] = $rule->message;
                    return;
                }
                break;
            case 'minlength' :
                if (!(self::longerThan($value, $rule->param))) {
                    self::$errors[$rule->field_name] = $rule->message;
                    return;
                }
                break;
            case 'maxlength' :
                if (!(self::shorterThan($value, $rule->param))) {
                    self::$errors[$rule->field_name] = $rule->message;
                    return;
                }
                break;
            case 'email' :
                if (!(self::asEmail($value))) {
                    self::$errors[$rule->field_name] = $rule->message;
                    return;
                }
                break;
            case 'phonenumber' :
                if (!(self::asPhoneNumber($value))) {
                    self::$errors[$rule->field_name] = $rule->message;
                    return;
                }
                break;
        }
    }

}

In the controller, everything is written as follows:
public function indexAction()
    {
        if (isset($_POST['submit'])){

            $name = $_POST['name'];

            Validator::addRule(
                'name',
                'Поле name обязательное',
                'required');
            Validator::addRule(
                'name',
                'Имя должно состоять не менне чем из 2-х символов',
                'minlength',
                3);

            Validator::addEntries($_POST);
            Validator::validate();

            $errors = Validator::getErrors();

        }
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikita Reutov, 2018-07-22
@Black_Tafita

To get data from the database, you must use a model, in this case, the User model.
Then you simply connect your model to any class you need and take what you need from the database using model methods

Y
Yan-s, 2018-07-22
@Yan-s

There are a lot of adequate validation components, see symphony, for example. Why drag some kind of muddy code. The same, by the way, about "I'm writing my bike, i.e. OOP, MVC framework". Frameworks are written differently, use ready-made components to the maximum.
Yeah, you can't, you have a model for that. You must call the appropriate model method from your validator.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question