Changing error 'cannot be blank' in Yii - php

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
);
}
}

Related

Creating a custom validation error message in CodeIgniter4

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'
],
])){
...
}

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.

cakephp3 custom validation

I have a duration field that sometimes can be empty and sometimes can't, depending on the other data sent by the form. So I'm trying to do custom validation in CakePHP3.
In my table I did
public function validationDefault(Validator $validator)
{
$validator
->add('duration', 'durationOk', [
'rule' => 'isDurationOk',
'message' => 'duration is not OK',
'provider' => 'table'
]);
return $validator;
}
public function isDurationOk($value, $context)
{
// do some logic
return false; // Always return false, just for test
}
Now when I set the value for duration field I get an 'duration is not OK' error (as expected). But when I let the value empty I get a 'This field cannot be left empty' error.
So I added:
->allowEmpty('duration');
But in this case when duration is empty I don't get an error at all.
Am I doing something wrong or it's just me don't understanding how validation works?
Let me read the book for you:
Conditional Validation
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.
Additionally, you can provide a callable function that will determine
whether or not a particular rule should be applied:
'on' => function ($context) {
// Do your "other data" checks here
return !empty($context['data']['other_data']);
}
So just define the conditions depending on your "other data" in the callback to apply the rule only when the conditons are true.
Alternatively you can manipulate the plain form data even before it gets validated in the beforeMarshal() callback of the table and change the form data as needed or load another validator or modify the validator.

Cake PHP - Form Validiation doesn't work

my CakePHP (1.2.5.) doesn't validate my form correct.
$this->UserData->save($this->data);
gives me always a true value back. I can't find the problem. The label for UserData.nichname works.
That's the View:
<?php
echo $form->create('UserData');
echo $form->error('UserData.nick_name');
echo $form->input('UserData.nick_name', array('id' => 'UserDatanick_name', 'rule' => 'alphaNumeric', 'label' =>'Nickname:', 'error' =>'false'));
echo $form->end( array( 'label' => ' Save ') );
?>
Here is my Controller:
class UserDatasController extends AppController {
var $name = 'UserDatas';
function add(){
if (!empty ($this->data)){
$this->UserData->create();
if ($this->UserData->save($this->data)){
$this->Session->setFlash('input is valid');
} else {
$this->Session->setFlash('input is not valid');
}
}
}
}
The rules for are not in the model, that's the reaseon i don't post it.
What else is necessary for a validation?
Thanks in advance
Steve
The validation rules have to be defined in the model, not in the view, see also the chapter about data validation in the cakebook.
^^ also check what your files are called.
you have named your model file user_data.php right? and your controller user_data_controller.php?
Note the underscores because of your CamelCasing. If you get the model file name wrong, it wont complain but will instead use a default magic model - which could be why your validation rules within the model didnt get picked up.
I believe you only specify the rules in the model, but the label would be kept in the $form->input() function

Categories