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.
Related
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'
],
])){
...
}
I want to validate some fields from validationDefault() function not all because of conditions but did not find any solution.
Example:
public function validationDefault(Validator $validator) {
$validator
->requirePresence('title', 'create')
->notEmpty('title');
$validator
->requirePresence('inquiry')
->allowEmpty('inquiry');
$validator
->requirePresence('dosage')
->allowEmpty('dosage');
$validator
->requirePresence('dosage_occurance')
->integer('dosage_occurance')
->allowEmpty('dosage_occurance');
return $validator;
}
Note: Response coming from two diffrent form first contains(title and inquiry) other contains(title, dosage and dosage_occurance).
I want to validate it from validationDefault() but it give me error
"dosage_occurance": {
"_required": "This field is required"
}
when I am not sending dosage_occurance which is correct but according to condition it is wrong.
using fieldList while creating new entity but it is not working.
Thanks
You want conditional validation.
Taken from the documentation:
When defining validation rules, you can use the on key to define when a validation rule should be applied. If left undefined, the rule will always be applied. Other valid values are create and update. Using one of these values will make the rule apply to only create or update operations.
Read the whole documentation page.
Example taken from there, pay attention to the on part.
$validator->add('picture', 'file', [
'rule' => ['mimeType', ['image/jpeg', 'image/png']],
'on' => function ($context) {
return !empty($context['data']['show_profile_picture']);
}
]);
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.
Currently the Validator in Laravel only appears to return one error message per field, despite the field potentially having multiple rules and messages. (Note: I'm currently passing an empty array as $data to Validator::make)
What I'm trying to do is build an array of each field's rules and messages that could potentially be re-used for front end validation. Something like this:
{
"name": {
"required": [
"The name field is required."
],
"max:255": [
"The name field may not be greater than 255."
]
},
"email": {
"required": [
"The email field is required."
],
"email": [
"The email field must be a valid email address."
],
"max:255": [
"The email field may not be greater than 255."
]
}
}
The getMessage method in Illuminate\Validation\Validator looks like it would get me close to being able to construct something myself, however it is a protected method.
Does anyone know of a way to get a Validator instance to output all rules and messages?
Currently the Validator in Laravel only appears to return one error message per field, despite the field potentially having multiple rules and messages.
Validation of given field stops as soon as a single validation rule fails. That's the reason you're getting only single error message per field.
As of fetching the validation messages like in the example you provided, Laravel's validator does not provide such option, but you could easily achieve that by extending the Validator class.
First, create your new class:
<?php namespace Your\Namespace;
use Illuminate\Validation\Validator as BaseValidator;
class Validator extends BaseValidator {
public function getValidationMessages() {
$messages = [];
foreach ($this->rules as $attribute => $rules) {
foreach ($rules as $rule) {
$messages[$attribute][$rule] = $this->getMessage($attribute, $rule);
}
}
return $messages;
}
}
As you can see the output is a bit different than your example. There is no need to return an array of messages for given attribute and rule, as there will be always only one message in the array, so I'm just storing a string there.
Second, you need to make sure that your validator class is used. In order to achieve that, you'll need to register your own validator resolver with Validator facade:
Validator::resolver(function($translator, array $data, array $rules, array $messages, array $customAttributes) {
return new \Your\Namespace\Validator($translator, $data, $rules, $messages, $customAttributes);
});
You can do this in your AppServiceProvider::boot() method.
Now, in order to get validation messages for given validator, you just need to call:
Validator::make($data, $rules)->getValidationMessages();
Keep in mind this code hasn't been tested. Let me know if you see any issues or typos with the code and I'll be more than happy to get that working for you.
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
);
}
}