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() { return [ ['birth_date', 'checkDateFormat'], // other rules ]; } 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.')); } }
The error message doesn't appear under the field in the form view when I push the submit button, while other rules like the required email and password appear.
I'm working on the Signup native form, so to be sure that it is not a filed problem, I've set the rule
['username', 'checkDateFormat']
and removed all the other rules related to the username field, but the message doesn't appear either for it.
I've tried passing nothing as parameters to checkDateFormat
, I've tried to explicitly pass the field's name to addError()
$this->addError('username', '....');
but nothing appears.
Which is the correct way to set a custom validation function?
To enable AJAX validation for a single input field, configure the enableAjaxValidation property of that field to be true and specify a unique form id : use yii\widgets\ActiveForm; $form = ActiveForm::begin([ 'id' => 'registration-form', ]); echo $form->field($model, 'username', ['enableAjaxValidation' => true]); // ...
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']);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With