Yii2: how to use custom validation function for activeform?

前端 未结 12 1154
独厮守ぢ
独厮守ぢ 2020-12-25 14:18

In my form\'s model, I have a custom validation function for a field defined in this way

class SignupForm extends Model
{
    public function rules()
    {
          


        
12条回答
  •  礼貌的吻别
    2020-12-25 14:52

    Although it's an old post i thought I should answer.

    You should create a Custom Validator Class and to create a validator that supports client-side validation, you should implement the yii\validators\Validator::clientValidateAttribute() method which returns a piece of JavaScript code that performs the validation on the client-side. Within the JavaScript code.

    You may use the following predefined variables:

    attribute: the name of the attribute being validated.

    value: the value being validated.

    messages: an array used to hold the validation error messages for the attribute.

    deferred: an array which deferred objects can be pushed into (explained in the next subsection).

    SO that means you can use messages array to push your messages to the client end on runtime within the javascript code block in this method.

    I will create a class that includes dummy checks that could be replaced the way you want them to. and change the namespace according to your yii2 advanced or basic.

    Custom Client-side Validator

    namespace common\components;
    use yii\validators\Validator;
    
    class DateFormatValidator extends Validator{
    public function init() {
            parent::init ();
            $this->message = 'You entered an invalid date format.';
        }
    
        public function validateAttribute( $model , $attribute ) {
    
            if ( /*SOME CONDITION TO CHECK*/) {
                $model->addError ( $attribute , $this->message );
            }
        }
    
        public function clientValidateAttribute( $model , $attribute , $view ) {
    
            $message = json_encode ( $this->message , JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
            return <<

    and then inside your model SigupForm add the rule

    ['birth_date', 'common\components\DateFormatValidator'],
    

    Deferred Validation

    You can even add ajax calls inside the clientValidateAttribute function and on the base of the result of that ajax call you can push message to the client end but you can use the deferred object provided by yii that is an array of Deferred objects and you push your calls inside that array or explicitly create the Deferred Object and call its resolve() method.

    Default Yii's deferred Object

    public function clientValidateAttribute($model, $attribute, $view)
    {
        return <<

    More about Deferred Validation

提交回复
热议问题