Custom error message not working for custom rule, see variable $messages uniqueTeamNameForcomp.
Custom rule is fine, custom message for rule:required is fine also.
The error message that shows for the rule uniqueTeamNameForComp is "unique_team_name_for_comp" when it should be reading the error message "This name already exist for this competition".
CONTROLLER:
public function store(Request $request){
$rules = [
'name' => 'required|uniqueTeamNameForComp:'.$request->compzid,
'compz' => 'required'
];
$messages = array(
'uniqueTeamNameForComp' => 'This name already exist for this competition',
'required' => 'this works'
);
$this->validate($request,$rules,$messages);
}
SERVICE PROVIDER:
public function boot()
{
Validator::extend('uniqueTeamNameForComp', function ($attribute, $value, $parameters, $validator) {
$competitionId = $parameters[0];
return count(Tteam::where("comp_id", "=", $competitionId)->whereName($value)->get()) == 0;
});
}
The output you're seeing from Laravel is actually giving you a hint. It expects the custom messages to be keyed by the validation rule in snake case, not camel case.
$messages = array(
'unique_team_name_for_comp' => 'This name already exist for this competition',
'required' => 'this works'
);
Related
I have created a custom validation rule and I am using it to validate a data field in a FormRequest.
However, I would like to use a different message for this field and not the default message that is set in the Rule's message() method.
So, I tried using the method messages() inside of the FormRequest using a key of the field name and the rule (in snake case)
public function rules()
{
return [
'clients' => [
new ClientArrayRule(),
],
];
}
public function messages()
{
return [
'clients.client_array_rule' => "clients should be a valid client array"
];
}
The error message did not change, I investigated a little inside the code of the validator and I found out that for custom rules, it uses the method validateUsingCustomRule that doesn't seem to care about custom messages.
Any ideas on how it can be overwritten or what would be the best way to do it?
For custom message on Laravel:
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'username' => 'required',
'password' => 'required',
'email' => 'required',
'age' => 'required|gte:4',
];
}
/**
* Get the error messages for the defined validation rules.
*
* #return array
*/
public function messages()
{
return [
'username.required' => 'Custom message',
'password.required' => 'Custom message',
'email.required' => 'Custom message',
'age.required' => 'Custom message',
'age.gte' => 'Custom message'
];
}
How can i make a custom validation rule to an input which value must be an integer and starting with 120?
I already read about making custom messages but didnt understand about rules.
I want to use a regex to validate the data. ^120\d{11}$ here is my regex.
I'm new in Laravel that's why cant now imagine how to do that.
A custom validation to use it in $this->validate($request, []);
Now i'm validating data like so:
$this->validate($request, [
'user_id' => 'integer|required',
'buy_date' => 'date',
'guarantee' => 'required|unique:client_devices|number',
'sn_imei' => 'required|unique:client_devices',
'type_id' => 'integer|required',
'brand_id' => 'integer|required',
'model' => 'required'
]);
The input that i want to add custom validation is guarantee
The quickest neatest way is an inline validator in your controller action:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'number' => [
'regex' => '/^120\d{11}$/'
],
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
return view('welcome');
}
Where number is the name of the field being submitted in the request.
If you have a lot of validation to do, you might want to consider using a Form Request instead, as a way of consolidating a lot of validation logic.
You can create custom validations in your controller as:
$name = Input::get('field-name')
$infoValidation = Validator::make(
array( // Input array
'name' => $name,
),
array( // rules array
'name' => array("regex:/^120\d{11}$"),
),
array( // Custom messages array
'name.regex' => 'Your message here',
)
); // End of validation
$error = array();
if ($infoValidation->fails())
{
$errors = $infoValidation->errors()->toArray();
if(count($errors) > 0)
{
if(isset($errors['name'])){
$response['errCode'] = 1;
$response['errMsg'] = $errors['name'][0];
}
}
return response()->json(['errMsg'=>$response['errMsg'],'errCode'=>$response['errCode']]);
}
Hope this helps.
Since Laravel 5.5, you can make the validation directly on the request object.
public function store(Request $request)
{
$request->validate([
'guarantee' => 'regex:/^120\d{11}$/'
]);
}
How can I write rule for input field like below:
{!! Form::number("amount[]",null,['min' => 0, 'class' => 'form-control col-xs-2 ']) !!}
I tried following which gave error: htmlentities() expects parameter 1 to be string, array given
$rules = array(
'amount[]' => 'required'
);
$this->validate($request, $rules);
Update:
I tried this as suggested by a user, it's not redirecting it on page again. Below is controller method:
public function postEstimate(Request $request) {
$rules = array(
'amount' => 'required|array'
);
$this->validate($request, $rules);
}
I guess you got issues with what I explained so this is what I meant -
$rules = [];
$count_amounts = count($request->input('amount'));
foreach (range(0, $count_amounts) as $number) {
$rules['amount.' . $number] = 'required|integer|min:0';
}
This should check that each amount input you have is an integer and is bigger than 0 (like you defined in the html validation)
Instead try this:
private $rules = array(
'amount' => 'required|array',
);
public function postEstimate(Request $request) {
$this->validate($request, $this->rules);
}
or, try a validation with a 'amount' => 'required
im not sure about this 'amount' => 'required|array
For custom rules implementation of integer type value check of an array
firstly open the following file
/resources/lang/en/validation.php
Then add the custom message
'numericarray' => 'The :attribute must be numeric array value.',
'requiredarray' => 'The :attribute must required all element.',
Again open the another file
/app/Providers/AppServiceProvider.php
Now add custom validation code in the boot function.
public function boot()
{
$this->app['validator']->extend('numericarray', function ($attribute, $value, $parameters)
{
foreach ($value as $v) {
if (!is_int($v)) {
return false;
}
}
return true;
});
$this->app['validator']->extend('requiredarray', function ($attribute, $value, $parameters)
{
foreach ($value as $v) {
if(empty($v)){
return false;
}
}
return true;
});
}
Now you can use the requiredarray for all element required of array. And also use the numericarray for integer type value check of array
$this->validate($request, [
'field_name1' => 'requiredarray',
'field_name2' => 'numericarray'
]);
if you expect amount as an array the rules should be
$rules = array(
'amount' => 'required|array'
);
check the doc
If your not redirecting or getting a validation error means there is no validation error
just dd($request->input('amount')) in the controller and check its a array or not if it's a array then validations will pass.
Custom error message in form request class in not working, my form request class given below,
class FileRequest extends Request {
protected $rules = [
'title' => ['required', 'max:125'],
'category_id' => ['required', 'integer', 'exists:file_categories,id']
];
public function authorize() {
return true;
}
public function rules() {
return $this->rules;
}
public function message() {
return [
"category_id.required" => 'Category required',
];
}
}
Here when category_id is null, showing error message category id is required instead of Category required in laravel 5.1?
It is messages, not message.
Change
public function message()
to
public function messages()
You do not need to create any functions to change these messages. In the file /resources/lang/en/validation.php you can add translations for the field names you are using in the attributes array.
In your case, you would do the following:
return [
'attributes' => [
'category_id' => 'Category'
],
];
Now, whenever the category_id doesn't pass the validations, the error message will display this simply as Category.
I have created a custom error function by creating a class;
<?php
class CoreValidator extends Illuminate\Validation\Validator
{
public function validatePostcode($attribute, $value, $parameters = null)
{
$regex = "/^((GIR 0AA)|((([A-PR-UWYZ][0-9][0-9]?)|(([A-PR-UWYZ][A-HK-Y][0-9][0-9]?)|(([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY])))) [0-9][ABD-HJLNP-UW-Z]{2}))$/i";
if(preg_match($regex ,$value)) {
return true;
}
return false;
}
}
I reference it in my model;
public static $rules = array(
'first_name' => 'required|Max:45',
'surname' => 'required|Max:45',
'address_line_1' => 'required|Max:255',
'address_line_2' => 'Max:255',
'address_line_3' => 'Max:255',
'town' => 'required|Max:45',
'county' => 'Max:45',
'postcode' => 'required|Postcode',
'phone_number' => 'required|Max:22'
);
It has been registered in my global.php;
Validator::resolver(function($translator, $data, $rules, $messages) {
return new CoreValidator($translator, $data, $rules, $messages);
});
It all works well, but the error message it returns is
validation.postcode
How/where do I set a custom error message for this?
I have tried setting app/lang/en/validation.php with (neither work);
'custom' => array(
"validation.postcode" => "my error message 1",
"postcode" => "my error message 2"
)
P.S. I know that there is a regex validation method already, but this problem is more generic for me.
I think I have cracked it.
I added the message to the main array in app/lang/en/validation.php, not into the custom sub-array.
return array(
...
"url" => "The :attribute format is invalid.",
"postcode" => "my error message 2",
...
)
If this isn't the correct way, then someone is free to correct me.
You can use setCustomMessages() method to assign custom messages like the bellow code
<?php
class CoreValidator extends Illuminate\Validation\Validator
{
private $custom_messages = array(
"customvalidation" => "my error message.",
);
public function __construct($translator, $data, $rules, $messages = array(), $customAttributes = array())
{
parent::__construct($translator, $data, $rules, $messages, $customAttributes);
$this->setCustomMessages($this->custom_messages);
}
public function validateCustomvalidation($attribute, $value, $parameters = null)
{
// validation code here
}
}
maybe this code more better :
// for example I am using sub-array custom at default validation file, but you can do it in other file as you wishes.
..other..
'custom' => array(
'email' => array(
'required' => 'We need to know your e-mail address!',
),
"required" => "Hey!!! don't forget at :attribute field is required.",
),
..other..
// you can determine your custom languages at your wishes file
$messages = \Lang::get('validation.custom');
Validator::make($input, $rules, $messages);
From documentation:
In some cases, you may wish to specify your custom messages in a language file instead of passing them directly to the Validator. To do so, add your messages to custom array in the app/lang/xx/validation.php language file.
'custom' => array(
'email' => array(
'required' => 'We need to know your e-mail address!',
),
),
That means, in your case,
'custom' => array(
'postcode' => array(
'PostCode' => 'error message for PostCode rule',
'required' => 'error message for required rule',
),
),
If you want to utilize the custom validation messages array in app/lang/xx/validation.php, the correct way is as follows:
'custom' => array(
'formFieldName' => array(
'postcode' => 'error message for PostCode rule',
'iamalwayslowercase' => 'error message for this rule'
),
),
Note that you use the name of the form field and then in the array you use the lowercased name of the rule.
The code below also works perfectly, take note of the underscore on the index of the $customValidatorMessages array. Hope it helps someone :-)
class CoreValidator extends Illuminate\Validation\Validator
{
/**
* The array of custom validator error messages.
*
* #var array
*/
protected $customValidatorMessages = array();
public function validatePostcode($attribute, $value, $parameters = null)
{
$regex = "/^((GIR 0AA)|((([A-PR-UWYZ][0-9][0-9]?)|(([A-PR-UWYZ][A-HK-Y][0-9][0-9]?)|(([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY])))) [0-9][ABD-HJLNP-UW-Z]{2}))$/i";
if(preg_match($regex ,$value)) {
return true;
}
$this->customValidatorMessages['post_code'] = 'Postcode error message.';
$this->setCustomMessages($this->customValidatorMessages);
return false;
}
}