Answer the question
In order to leave comments, you need to log in
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;
}
Answer the question
In order to leave comments, you need to log in
['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;
}
}
}
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
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 questionAsk a Question
731 491 924 answers to any question