How to validate input in Yii?

Member

by darion , in category: PHP Frameworks , 2 years ago

How to validate input in Yii?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , 2 years ago

@darion 

In Yii, you can use several built-in validators to validate form input. Here are the steps to validate input in Yii:

  1. Define validation rules: In your model class, define the validation rules for each attribute. For example:
1
2
3
4
5
6
7
8
public function rules()
{
    return [
        [['name', 'email'], 'required'],
        ['email', 'email'],
        ['age', 'integer', 'min' => 18],
    ];
}


  1. Perform validation: In your controller, create a model instance and call the validate() method on it. For example:
1
2
3
4
5
6
7
$model = new User();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
    // Input is valid, perform further actions
} else {
    // Input is invalid, show form with error messages
    return $this->render('create', ['model' => $model]);
}


  1. Display error messages: In your view, use the getErrors() method to display error messages. For example:
1
2
3
4
5
6
7
if ($model->hasErrors()) {
    foreach ($model->getErrors() as $attribute => $errors) {
        foreach ($errors as $error) {
            echo $model->getAttributeLabel($attribute) . ' ' . $error . '';
        }
    }
}


With these steps, you can validate input in Yii using built-in validators. You can also create custom validators if needed.