Hi guys,
I have the following custom standalone validator:
<?php
namespace myproject\validators;
use Yii;
use yii\base\InvalidConfigException;
use yii\web\JsExpression;
use yii\helpers\Json;
use yii\validators\Validator;
/**
* bla bla bla
*/
class AlphaDashDotValidator extends Validator
{
/**
* @var string the regular expression used to validate the attribute value.
* @see http://www.regular-expressions.info/email.html
*/
public $pattern = '/^([-a-z0-9_.-])+$/i';
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if ($this->message === null) {
$this->message = Yii::t('yii', '{attribute} cannot contain anything other than alpha-numeric characters, underscores, dashes or dots.');
}
}
/**
* @inheritdoc
*/
protected function validateValue($value)
{
$valid = true;
// make sure string length is limited to avoid DOS attacks
if (!is_string($value) || strlen($value) >= 320) {
$valid = false;
} elseif (!preg_match($this->pattern, $value, $matches)) {
$valid = false;
}
return $valid === true ? null : [$this->message, []];
}
/**
* @inheritdoc
*/
public function clientValidateAttribute($object, $attribute, $view)
{
$options = [
'pattern' => new JsExpression($this->pattern),
'message' => Yii::$app->getI18n()->format($this->message, [
'attribute' => $object->getAttributeLabel($attribute),
], Yii::$app->language),
];
$options['skipOnEmpty'] = 1;
yii\validators\ValidationAsset::register($view);
return 'yii.validation.regularExpression(value, messages, ' . Json::encode($options) . ');';
}
}
When I use this validator, I have to use it like this:
User Model:
public function rules()
{
return [
[['username'], 'myproject\validators\AlphaDashDotValidator'],
];
}
Is there any way I can create an alias for this validation like the builtInValidators? I want to use the rule like ‘alpha-dash-dot’ instead of writing the whole class namespace.
Thanks