Yii2: how to use custom validation function for activeform?

前端 未结 12 1157
独厮守ぢ
独厮守ぢ 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:29

    Are you by any chance using client side validation? If you do then you have to write a javascript function that would validate the input. You can see how they do it here:

    http://www.yiiframework.com/doc-2.0/guide-input-validation.html#conditional-validation

    Another solution would be to disable client validation, use ajax validation, that should bring back the error too.

    Also make sure that you have not overwritten the template of the input, meaning make sure you still have the {error} in there if you did overwrite it.

    0 讨论(0)
  • 2020-12-25 14:30

    Are you sure the first parameter of addError shouldn't be like this

    $this->addError(**'attribute'**, Yii::t('user', 'You entered an invalid date format.'));
    
    0 讨论(0)
  • 2020-12-25 14:31

    Did you read documentation?

    According to the above validation steps, an attribute will be validated if and only if it is an active attribute declared in scenarios() and is associated with one or multiple active rules declared in rules().

    So your code should looks like:

    class SignupForm extends Model
    {
        public function rules()
        {
            return [
                ['birth_date', 'checkDateFormat'],
    
                // other rules
            ];
        }
    
        public function scenarios()
        {
            $scenarios = [
                'some_scenario' => ['birth_date'],
            ];
    
            return array_merge(parent::scenarios(), $scenarios);
        }
    
        public function checkDateFormat($attribute, $params)
        {
            // no real check at the moment to be sure that the error is triggered
            $this->addError($attribute, Yii::t('user', 'You entered an invalid date format.'));
        }
    }
    

    And in controller set scenario, example:

    $signupForm = new SignupForm(['scenario' => 'some_scenario']);
    
    0 讨论(0)
  • 2020-12-25 14:31

    To make custom validations in yii 2 , you can write custom function in model and assign that function in rule. for eg. I have to apply password criteria in password field then I will write like this in model.

    public function rules()
    {
        return [
            ['new_password','passwordCriteria'],
        ];
    }
    
    public function passwordCriteria()
    {
        if(!empty($this->new_password)){
            if(strlen($this->new_password)<8){
                $this->addError('new_password','Password must contains eight letters one digit and one character.');
            }
            else{
                if(!preg_match('/[0-9]/',$this->new_password)){
                    $this->addError('new_password','Password must contain one digit.');
                }
                if(!preg_match('/[a-zA-Z]/', $this->new_password)){
                    $this->addError('new_password','Password must contain one character.');
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-25 14:33

    I stumbled on this when using the CRUD generator. The generated actionCreate() function doesn't include a model validation call so custom validators never get called. Also, the _form doesn't include and error summary.

    So add the error summary to the _form.

    <?= $form->errorSummary($model); ?>
    

    ...and add the validation call - $model->validate() - to the controller action

    public function actionCreate()
    {
        $model = new YourModel();
    
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {...
    
    0 讨论(0)
  • 2020-12-25 14:39

    Try forcing the validation on empty field

    ['birth_date', 'checkDateFormat', 'skipOnEmpty' => false, 'skipOnError' => false],
    

    Also, make sure you don't assign id to your birth_date field in your view.

    If you do have id for your birth_date, you need to specify the selectors

    <?= $form->field($model, 'birth_date', ['selectors' => ['input' => '#myBirthDate']])->textInput(['id' => 'myBirthDate']) ?>
    
    0 讨论(0)
提交回复
热议问题