Laravel Custom Validation for multi-language application - laravel

I am using Laravel Standard Validation, but I want to customize it because I am using multi language in my application, so I have to customize the message.
$rule_validation = [
'phone' => 'required|max:20|min:6|regex:/^[0-9]+$/',
'agree_promo_code' => request('promo_code') ? 'accepted' : '',
'terms_of_services' => 'accepted',
'aware' => 'accepted'
];
Now I want to write customize validation message for agree_promo_code
I know to write message for phone, but having doubt in agree_promo_code, terms_of_services and aware.
Can anyone help me out to resolve this issue
But please keep in mind about the language. Thank you

You can pass second array to your validate function like
$this->validate($request,[
'phone' => 'required|max:20|min:6|regex:/^[0-9]+$/',
'agree_promo_code' => request('promo_code') ? 'accepted' : '',
'terms_of_services' => 'accepted',
'aware' => 'accepted'
],[
'phone.required' => trans('validation.phone'),
'agree_promo_code.accepted' => trans('validation.agree_promo_code'),
'terms_of_services.accepted' => trans('validation.terms_of_services'),
'aware.accepted' => trans('validation.aware'),
]);
and inside your resources/lang/{lang}/validation.php file ({lang} is your language directory).
you can do something like
return [
'phone' => 'Phone validation message',
'agree_promo_code' => 'agree_promo_code validation message',
'terms_of_services' => 'terms_of_services validation message',
];
So it will set your messages according to respective language.

As you set your Language files for respective language
you need to create validation.php file under respective language folder
and add custom message for each field for each type of validation applied
for example if you have name field and validation check is required
so in your language folder's validation file you will write as below
<?php
return [
'custom' => [
'name' => [
'required' => 'O campo nome é obrigatório.'
]
];
rest all language check will be handled by Laravel itself while displaying validation error messages as per your locale language selected for session

Related

How to use custom translations for requests in Laravel?

Documentation says to create directory with file by path: resources/lang/xx/validation.php.
Then add content of validation words:
return ['custom' => [
'email' => [
'required' => 'We need to know your e-mail address!',
],
]];
How to use this for Creating Form Requests where is going validation?
This is just for deploying custom validation messages, e.g. whenever 'email' is 'required' it will return this message in place of the default message: The email field is required.
If you want to replace all the other messages take a look at /resources/lang/en/validation.php here and see all the basic messages which you can replace with your local language versions in your /resources/lang/xx/validation.php
If you want a custom message, find the custom array at line 130 and change to:
'custom' => [
'price' => [
'required' => 'The price is required! Please supply one.',
],
],
Then, be sure to set your app locale, e.g.
Route::get('welcome/{locale}', function ($locale) {
App::setLocale($locale);
//
});
Or if your entire app is in another language, you could set locale in your /config/app.php on line 81.
Your usual validator will now use the messages in /resources/lang/locale/validation.php

Handling CodeIgniter form validation (rule keys and data types)

Okay, so I've been searching for a while this question, but couldn't find an answer (or at least some direct one) that explains this to me.
I've been using CodeIgniter 3.x Form Validation library, so I have some data like this:
// Just example data
$input_data = [
'id' => 1,
'logged_in' => TRUE,
'username' => 'alejandroivan'
];
Then, when I want to validate it, I use:
$this->form_validation->set_data($input_data);
$this->form_validation->set_rules([
[
'field' => 'id',
'label' => 'The ID to work on',
'rules' => 'required|min_length[1]|is_natural_no_zero'
],
[
'field' => 'username',
'label' => 'The username',
'rules' => 'required|min_length[1]|alpha_numeric|strtolower'
],
[
'field' => 'logged_in',
'label' => 'The login status of the user',
'rules' => 'required|in_list[0,1]'
]
]);
if ( $this->form_validation->run() === FALSE ) { /* failed */ }
So I have some questions here:
Is the label key really necessary? I'm not using the Form Validation auto-generated error messages in any way, I just want to know if the data passed validation or not. Will something else fail if I just omit it? As this will be a JSON API, I don't really want to print the description of the field, just a static error that I have already defined.
In the username field of my example, will the required rule check length? In other words, is min_length optional in this case? The same question for alpha_numeric... is the empty string considered alpha numeric?
In the logged_in field (which is boolean), how do I check for TRUE or FALSE? Would in_list[0,1] be sufficient? Should I include required too? Is there something like is_boolean?
Thank you in advance.
The "label" key is necessary, but it can be empty.
The "required" rule does not check length, nor does the "alpha_numeric". It checks that a value is present, it does not check the length of said value. For that, there is min_length[] and max_length[].
If you're only passing a 0 or 1, then this is probably the easiest and shortest route.

Laravel Validation custom messages using nested attributes

I would like to ask for some advices about Laravel Validation...
Let's say I've got an input named invoiceAddress[name] and in a controller I've got a rule
$rule = ['invoiceAddress.name' => 'required',];
or just a
$validator = \Validator::make($request->all(), [
'invoiceAddress.name' => 'required',
]);
now, inside custom validation language file validation.php, am I able to nest attributes somehow? like:
'required' => ':attribute is mandatory',
'attributes' => [
'invoiceAddress' => [
'name' => 'blahblah'
],
],
If I try to nest the attribute the way above, i get
ErrorException
mb_strtoupper() expects parameter 1 to be string, array given
because I am using a field (as above)
['name' => 'blahblah']
I am trying to get custom messages using the file and the :attribute directive (as mentioned in the code above).
I am basically trying to do this How to set custom attribute labels for nested inputs in Laravel but i get the mentioned error...
Thank you in advance...
A Note On Nested Attributes
If your HTTP request contains "nested" parameters, you may specify them in your validation rules using "dot" syntax:
$this->validate($request, [
'title' => 'required|unique:posts|max:255',
'author.name' => 'required',
'author.description' => 'required',
]);
Reference: https://laravel.com/docs/5.3/validation#quick-writing-the-validation-logic (A Note On Nested Attributes Section)

CodeIgniter custom validation errors for each rule per each field

I'm using CodeIngiter 2.1 and I wanna define custom validation errors for each rule per each field. The fields are as follows.
array(
'field' => 'firstname',
'rules' => 'required',
'error' => 'This field cannot be empty.'
),
array(
'field' => 'email',
'rules' => 'required',
'error' => 'The email cannot be empty.'
)
But In CodeIgniter only one error message is defined for one rule. So how to override that one and Please suggest some solutions for getting different errors for perticular field. The work is more appreciated.
Try using the CI function :
set_message();
All of the native error messages are located in the following language file:
language/english/form_validation_lang.php
To set your own custom message you can either edit that file, or use the following function:
$this->form_validation->set_message('rule', 'Error Message');
for more about set_message here
Hope it will help;
I recently made this custom error message option for my codeigniter 3.0-dev applicaiton. Hope this helps anyone out there.
https://gist.github.com/abdmaster/7287962
To use it (example),
$this->form_validation->set_rules('name','Name','required|alpha',array('required' => 'Please fill the field %s .');`
It will work with Base models like jamierumbelow's MY_Model. In your model, you do something like this:
public $validate = array(
'display_name' => array(
'field' => 'display_name',
'label' => 'Display Name',
'rules' => 'trim|required|xss_clean|valid_fullname|is_unique[users_model.display_name]',
'error_msg' => array(
'is_unique' => 'The name in %s is already being used by someone.',
),
),
);
Rest are how we are use normally. Hope these examples are enough.
I haven't tried in v2.1.x but hopefully this will work. Maybe have to do some minor adjustments.

cakePHP optional validation for file upload

How to make file uploading as optional with validation?
The code below validates even if i didn't selected any file.
I want to check the extension only if i selected the the file.
If i am not selecting any file it should not return any validation error.
class Catalog extends AppModel{
var $name = 'Catalog';
var $validate = array(
'name' => array(
'rule' => '/^[a-z0-9 ]{0,}$/i',
'allowEmpty' => false,
'message' => 'Invalid Catalog name'
),
'imageupload' => array(
'rule' => array('extension',array('jpeg','jpg','png','gif')),
'required' => false,
'allowEmpty' => true,
'message' => 'Invalid file'
),
);
}
thanks in advance
"I assign $this->data['Catalog']['image'] = $this->data['Catalog']['imageupload']['name'];"
So by the time you save your data array, it looks something like this I assume:
array(
'image' => 'foobar',
'imageupload' => array(
'name' => 'foobar',
'size' => 1234567,
'error' => 0,
...
)
)
Which means, the imageupload validation rule is trying to work on this data:
array(
'name' => 'foobar',
'size' => 1234567,
'error' => 0,
...
)
I.e. the value it's trying to validate is an array of stuff, not just a string. And that is unlikely to pass the specified validation rule. It's also probably never "empty".
Either you create a custom validation rule that can handle this array, or you need to do some more processing in the controller before you try to validate it.
Concept:
In Controller, before validating, or saving (which does validation automatically by default) check if any file is uploaded. If not uploaded, then unset validator for the file field.
Sample code:
Controller
// is any image uploaded?
$isNoFileUploaded = ($this->request->data['Model']['field_name']['error'] == UPLOAD_ERR_NO_FILE) ? true : false ;
if ($isNoFileUploaded) {
$this->Model->validator()->remove('field_name');
}
Notes:
This solution comes under preprocessing as one of the two alternative approaches (preprocessing in controller, custom validation in model) suggested by #deceze's answer

Resources