A
A
akula222016-01-13 17:53:55
Yii
akula22, 2016-01-13 17:53:55

How to create custom validation rule in yii2?

It is necessary that in the comments when posting, the length of one word does not exceed 150 characters.
I created a method for checking the length of each word in the text, but I don’t know how to attach it to the rules

public function lognWord($text)
    {
        $word = explode(" ", $text);

        for ($i = 0; $i < sizeof($word); $i++)
        {
            $check = strlen($word[$a]);
        }
        if ($check > self::LONG_WORD) //  150
        {
            return true;
        }
        return false;
}

['post', 'longWord', 'targetClass' => 'Comments'],
ReflectionException
Class longWord does not exist

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vitaly Khomenko, 2016-01-13
@akula22

['post', 'validatorLongWords'],

public function validatorLongWords ( $attribute )
{
    $parts = explode( ' ', $this->$attribute );
    foreach ( $parts as $word ) {
        if ( strlen( $word ) > static::LONG_WORD ) { # Для UTF-8 и русского текста используем mb_strlen( $word )
            $this->addError( $attribute, 'Слишком длинное слово в строке, да...' );
            break; # или return;
        }
    }
}

A
Anton Natarov, 2016-01-13
@HanDroid

How difficult it is for you. Yii2 has its own line validator Documentation
In Ruls, just specify
/ not less than 4, but not more than 150
This is the only rule for the total length of a comment. If you need words to be no more than 150. You will have to split the input string into arrays of words and check with this validator.
To highlight all the logic, and use validation. It is possible to implement a built-in validator

S
Slava Kryvel, 2016-01-13
@kryvel

You need to write your own validator. See here for details
stackoverflow.com/questions/27805133/yii2-how-to-u...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question