Creating a custom validation error message in CodeIgniter4 - php

How can i create a custom error message for a custom validation. I'm using codeIgniter4
Okay guys so I'm a bit of a newbie with CI4 and I have created a custom validation file using the spark command ./spark make:validation and it works but the problem is I still don't know how to customize the error message too for instance when I try to validate the date 05-06-2022 the message is Validation.isWeekday, I want to let it say something meaningful like date is not a weekday.
This is how my validation looks like
namespace App\Validation;
class CustomDateValidation
{
public function isWeekday(string $date): bool
{
return date("N", strtotime($date)) < 6;
}
}
And my controller function looks a bit like this
if($this-validate(['date'=>'required|isWeekday'])){
...
}

You can pass a options array for each field you want validate instead of just the rules string:
if($this-validate([
'date'=> [
'rules' => 'required|isWeekday',
'errors' => [
'required' => 'The date field is required',
'isWeekday' => 'The date must be a weekday'
],
])){
...
}

Related

How to customise error message to add ID in Yii?

Currently I am using $form->error($user_model,'password') this function to show error message which gives me output as <div class="errorMessage">Please enter current password</div> but I want to add id in same div. What changes I have to do for that?
To customize error message you have to go to user model and change/add your message to function rules() array.
function rules() {
return [
['password', 'required', 'message' => 'Your custom message'],
];
}
Check CRequiredValidator class for more information.
To apply some custom ID:
$form->error($error_model, 'password', ['id' => 'My-super-custom-id']);
just it will break your error messages output when using yii-js methods.

CakePHP 3 - Cake trying to validate notEmpty for some reason

My table is throwing a default "notEmpty" validation error, even though I have not written any validation of the sort.
Basic validation in my Table class:
public function validationDefault(Validator $validator)
{
return $validator->requirePresence('my_field', 'create', 'Custom error message');
}
Data being set:
['my_field' => null]
As far as I can tell from the docs, this should not fail validation.
Key presence is checked by using array_key_exists() so that null values will count as present.
However, what is actually happening is that validation is failing with a message:
'my_field' => 'This field cannot be left empty'
This is Cake's default message for the notEmpty() validation function, so where is it coming from? I want it to allow the null value. My database field also allows NULL.
Edit
I have managed to solve the issue by adding allowEmpty() to the validation for that field. This would, therefore, seem to show that Cake assumes that if your field is required you also want it validate notEmpty() by default, even if you didn't tell it so.
This directly contradicts the documentation line I showed above:
Key presence is checked by using array_key_exists() so that null values will count as present.
So does the documentation need to be updated, or is it a bug?
Although it is not mentioned in the Cake 3 documentation, required fields are not allowed to be empty by default, so you have to explicitly state that the field is required and allowed to be empty.
public function validationDefault(Validator $validator)
{
return $validator
->requirePresence('my_field', 'create', 'Custom error message')
->allowEmpty('my_field', 'create');
}
This had me stumped for a while. The default behaviour is not at all intuitive. Here's some code that applies conditional validation on an array of scenarios coded as [ targetField, whenConditionalField, isConditionalValue ]
public function validationRegister()
{
$validator = new Validator();
$conditionals = [ ['shipAddress1','shipEqualsBill','N'], ['shipTown','shipEqualsBill','N'], ['shipPostcode','shipEqualsBill','N'] ];
foreach($conditionals as $c) {
if (!is_array($c[2])) $c[2] = [$c[2]];
// As #BadHorsie says, this is the crucial line
$validator->allowEmpty($c[0]);
$validator->add($c[0], 'notEmpty', [
'rule' => 'notEmpty',
'on' => function ($context) use ($c) {
return (!empty($context['data'][$c[1]]) && in_array($context['data'][$c[1]], $c[2]));
}
]);
}
return $validator;
}
So, in this case, if the user selects that the Shipping Address is not the same as the Billing Address, various shipping fields must then be notEmpty.

Yii Framework 2.0 Rules Date Validator

I am using Yii Framework 2.0. I have a form with a text input field which is meant for a date. I have read the Yii Framework 2.0 about the Class yii\validators\Validator and known all the validator keys which can be used inside of the rules() method in a model class. When I use the date key as below, it does not validate anything. It means that I still can put some text in that input field and can post the form.
When I changed it into boolean or email, I could see that it validates very well when I put something wrong in the input field. How can I validate a date value inside of an input field with Yii Framework 2.0?
My rules() method:
public function rules()
{
return [
[['inputfield_date'], 'required'],
[['inputfield_date'], 'safe'],
[['inputfield_date'], 'date'],
];
}
My view page:
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'inputfield_date')->textInput(); ?>
<?php ActiveForm::end(); ?>
Boy the Yii docs suck. They don't even give an example. Working from O'Connor's answer, this worked for me since I was assigning the value in 2015-09-11 format.
// Rule
[['event_date'], 'date', 'format' => 'php:Y-m-d']
// Assignment
$agkn->event_date = date('Y-m-d');
The docs don't even specify where format or timestampAttribute came from, or how to use them. It doesn't even say what the heck from_date and to_date are. And most of all, no examples!
Working solution. My rules() method:
public function rules()
{
return [
[['inputfield_date'], 'required'],
[['inputfield_date'], 'safe'],
['inputfield_date', 'date', 'format' => 'yyyy-M-d H:m:s'],
];
}
My form in the view page:
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'inputfield_date')->textInput(); ?>
<?php ActiveForm::end(); ?>
My method in controller:
if ($model->load(Yii::$app->request->post()) && $model->validate()):
if($model->save()):
// some other code here.....
endif;
endif;
Note that the date format depends on how you define your date format input field. Note once again that this is not an AJAX validator. After clicking on the submit button, you will see the error message if you enter something else which is not a date.
You can validate for date like this from model rules
public function rules(){
return [
[['date_var'],'date', 'format'=>'d-m-yy'],
[['from_date', 'to_date'], 'default', 'value' => null],
[['from_date', 'to_date'], 'date'],
];
}
Not 100% sure how it is in Yii2, but going out from Yii1 that had to look like this...
array('org_datetime', 'date', 'format'=>'yyyy-M-d H:m:s'),
(source: http://www.yiiframework.com/wiki/56/#hh8)
...I'd say i'd have to look something like this in Yii2:
['shopping_date', 'date', 'format' => 'yyyy-M-d H:m:s'],
Firstly, date validation relies on $model->validate(), so does not work inline but is only triggered by clicking Save (i.e. it's typically applied in actionCreate/actionUpdate).
Secondly, it's applied after other rules like 'required', and only if they pass, so even when you click Save, if anything else fails validation, those errors will show, but the date error will not.
In summary, date validation can only be tested by ensuring that all other rules pass and then clicking Save.

Laravel 4 custom validation error message

so I was trying to add a custom validation rules like this:
public function validateDateAfterField($attribute, $value, $params)
{
return strtotime($value) > strtotime($this->data[$params[0]]);
}
It takes the value and validate with another field in array of data being validate
I wanted it to produce an error message like this:
Event End Date must be a date after Event Start Date
Here is my custom validation message:
":attribute must be a date after :before"
I've added these custom validation attributes:
'attributes' => array(
'event_start'=>'Event Start Date',
'event_end' => 'Event End Date',
)
But when I cannot access it in my custom validation class, I've tried something like this:
return str_ireplace(":before", $this->attributes[$parameters[0]], $message);
but got an error Undefined property:CustomerValidator::attributes
Anyone knows how to do this properly?
Edit:
Extended it in my global.php
Validator::extend('date_after_field', 'CustomValidator#DateAfterField');
Validator::resolver(function($translator, $data, $rules, $messages)
{
return new CustomValidator($translator, $data, $rules, $messages);
});
I've found the answer after reading the documentation of the validator class.
By using $this->getAttribute($parameters[0]), I manage to get the custom attribute name.

Changing error 'cannot be blank' in Yii

Regarding handling error message in Yii: Commonly, Yii has configured form's validation, and when one of the required field isn't filled, then the error message will be shown as
"Blablabla cannot be blank."
How can I customize that error message? For example, I'd like to change into this:
"Blablabla tidak boleh kosong."
Its not clear what you are trying to do exactly, but
assuming you want to make a completely other message use :
public function rules()
{
return array(
array('title, content', 'required',
'message'=>'Please enter a value for {attribute}.'),
// ... other rules
);
}
if you, on the other hand, are looking for translations, the best way to do it is by setting your language in the config
'language'=>'de',
'components'=>array(
'coreMessages'=>array(
'basePath'=>null,
),
......
),
if your language is not defined, copy framework/messages/en/yii.php to protected/messages/{yourlanguage}/yii.php and start translating, even if you wonna add messages, put the them in protected/messages/{yourlanguage}/ and never translate them in the framwork, so you can update without a fuss.
I hope this is what you look for:
url: Yii docs
class Post extends CActiveRecord
{
public function rules()
{
return array(
array('title, content', 'required',
'message'=>'Please enter a value for {attribute}.'),
// ... other rules
);
}
}

Categories