Skip to content

Instantly share code, notes, and snippets.

@terdelyi
Last active July 11, 2018 09:15
Show Gist options
  • Save terdelyi/2734c24b534c3eb12f2209318834e273 to your computer and use it in GitHub Desktop.
Save terdelyi/2734c24b534c3eb12f2209318834e273 to your computer and use it in GitHub Desktop.
CraftCMS 3 - Custom model validation
<?php
// CraftCMS3 is using Yii2 framework which doesn't have a decoupled validator class.
// If you create a dummy model filled with the attributes coming from a POST request
// you can use custom validations for the incoming attributes.
$testPostData = [
'name' => 'Tamas Erdelyi',
'email' => '[email protected]'
];
$model = new TestModel();
$model->setAttributes($testPostData);
if ($model->validate()) {
var_dump($model->getAttributes());
} else {
var_dump($model->getErrors());
}
class TestModel extends \craft\base\Model
{
public $name;
public $email;
public function rules()
{
return [
[['name', 'email'], 'required'],
['email', 'email'],
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment