I need to validate a request with image and tags. How to return a common validation error message for tags.
$this->validate($request, [
'image' => 'required|image,
'tags.*' => 'string'
]);
Currecnt message is.
{
"image": [
"The image field is required."
],
"tags.0": [
"The tags.0 must be a string."
],
"tags.1": [
"The tags.1 must be a string."
]
}
Expected message is.
{
"image": [
"The image field is required."
],
"tags": [
"The tags must be a string."
]
}
Have you tried this,
$this->validate($request, [
'image' => 'required|image,
'tags.*' => 'string'
],$messages = [
'tags.*' => 'The tags must be a string.'
]);
I'm not quit sure but this might work for you.
I think you should try with similar below example:
public function messages()
{
$messages = [];
foreach ($this->request->get('tags') as $key => $val) {
$messages['tags.' . $key . '.string'] = 'The tags must be a string.'
}
return $messages;
}
Hope this work for you !!!
You can add messages with a * to your translation file, as documented.
'custom' => [
'tags.*' => [
'string' => 'The tags must be a string.',
]
],
Related
I am making an API that allows users to input some information like email, phone number, address ...
But if users input wrong phone nums, the validate error is
{
"message": "The given data was invalid.",
"errors": {
"phone": [
"The phone has already been taken."
]
}
}
As you can see the message returns is
"message": "The given data was invalid."
. But the message I expect is The phone has already been taken. How can I custom the message as I expect? With an email validator, the message is the same but the key is email. The message I expect is
"message": "The ... has already been taken. "
I'm using laravel 8 and validate in Request
Example a function rules()
public function rules()
{
return [
'profile_img' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:' . config('filesystems.max_upload_size'),
'name' => 'nullable|min:3',
'phone' => [
'required',
'numeric',
new UpdatePhoneRule(User::TYPE_CLIENT),
],
'email' => [
'nullable',
'email',
new UpdateEmailRule(User::TYPE_CLIENT),
]
];
}
Thanks
On the Request php file you can use this function failedValidation() and pass in a Validator. This way you can alter or customize the response if validation fails.
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Contracts\Validation\Validator;
protected function failedValidation(Validator $validator) {
throw new HttpResponseException(response()->json(['status'=>'failed',
'message'=>'unprocessable entity',
'errors'=>$validator->errors()->all()], 422));
}
Sample response is here..
{
"status": "failed",
"message": "unprocessable entity",
"errors": [
"The name must be a string.",
"One or more users is required"
]
}
As you can see the message is changed now you can do whatever you want on the response message.
Also you can try this
$validator->errors()->messages()[keyname]
You have to use unique in your validation
$this->validate(
$request,
[
'email' => 'required|unique:your_model_names',
'phone' => 'required|unique:your_model_names'
],
[
'email.required' => 'Please Provide Your Email Address For Better Communication, Thank You.',
'email.unique' => 'Sorry, This Email Address Is Already Used By Another User. Please Try With Different One, Thank You.',
'phone.required' => 'Your custom message',
'phone.unique' => 'The phone has already been taken'
]
);
You can do this in the lang file: resources/lang/en/validation.php. If all you want to do is change, for example, the message for a unique rule on an email field across the entire app you can do:
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
'email' => [
'unique' => 'This email is already registered...etc',
]
],
how to use js validator rules for two different forms in laravel ?
given below the code in controller
private $rules = [
"remark" => "required",
"tender_doc_path" => "required",
];
private $messages = [
"remark.required" => "The Remark Field is required.",
"tender_doc_path.required" => "The Tender Doc Path Field is required.",
];
this rules are used for two different form how it should be conditioned , the tender doc
filed is not required for second form
public function appoint_agency_edit($id)
{
$validator = \JSValidator::make($this->rules,$this->messages);
return view('ree.architect.appoint_agency',compact('validator'));
}
You can create two instances of your validator. Make sure you pass the rules for each instance properly.
private $rules = [
'sampleOne' => [
"remark" => "required",
"tender_doc_path" => "required",
],
'sampleTwo' => [
"remark" => "required",
"tender_doc_path" => "required",
]
];
private $messages = [
'sampleOne' => [
"remark.required" => "The Remark Field is required.",
"tender_doc_path.required" => "The Tender Doc Path Field is required.",
],
'sampleTwo' => [
"remark.required" => "The Remark Field is required.",
"tender_doc_path.required" => "The Tender Doc Path Field is required.",
]
];
public function appoint_agency_edit($id)
{
return view('ree.architect.appoint_agency', [
'sampleOne' => \JSValidator::make($this->rules['sampleOne'], $this->messages['sampleOne'),
'sampleTwo' => \JSValidator::make($this->rules['sampleTwo'], $this->messages['sampleTwo'])
]);
}
I have two fields
data[0][student]
data[0][teacher]
data[1][student]
data[1][teacher]
I tried this rule
$rules['data.*.student'] = 'required';
which gives this error
{
"error": {
"status_code": 412,
"validation": {
"data.student.*": [
"The data.*.student field is required."
]
},
"message": "Validation Failed"
}
}
how can I achieve this and make fields required if user missed this input field
data[student][0]?
For that you need to set a custom messages for rules inside Formrequest file.
You need to add rules and messages function Like this demostrated example:
Rules
public function rules()
{
return [
'item.*.name' => 'required|string|max:255',
'item.*.description' => 'sometimes|nullable|string|min:60',
'sku' => 'required|array',
'sku.*' => 'sometimes|required|string|regex:/^[a-zA-Z0-9]+$/',
'sku' => 'required|array',
'price.*' => 'sometimes|required|numeric'
];
}
Message
public function messages()
{
return [
'item.*.name.required' => 'You must have an item name.',
'item.*.name.max' => 'The item name must not surpass 255 characters.',
'item.*.description.min' => 'The description must have a minimum of 60 characters.',
'sku.*.regex' => 'The SKU must only have alphanumeric characters.',
'price.*.numeric' => 'You have invalid characters in the price field.'
];
}
I want that the fields payment_mb, payment_c and invoice_issuer are mandatory if the user introduces a value greater than "0" for field registration_type_price.
But its not working, the validation message is not appearing with "required_if:registration_type_price,>,0'". Do you know why?
$rules = [
...
'payment_mb' => 'required_without:payment_c|required_if:registration_type_price,>,0',
'payment_c' => 'required_without:payment_mb|required_if:registration_type_price,>,0',
'invoice_issuer' => 'required_if:registration_type_price,>,0',
];
$customMessages = [
...
'payment_mb.required_if' => 'The field payment methods is mandatory.',
'payment_c.required_if' => 'The field payment methods is mandatory.',
'invoice_issuer.required_if' => 'The field invoice issuer is mandatory..'
];
$this->validate($request, $rules, $customMessages);
try this one
$("#personal_detail_form").validate({
rules: {
full_name: {
lettersonly: true
},phone_number : {
number : true,
minlength:10,
maxlength:10
},city : {
lettersonly : true
},pin_code : {
digits : true,
minlength:6,
maxlength:6
},
Below is my server side validation in lumen :
$rules = array(
'prog_code' => 'required',
'payer_id' => 'required',
);
$validator = \Validator::make($post, $rules);
if (!$validator->fails()) {
try {
// Start Logic Here
} catch (\Exception $e) {
}
} else {
$errors = $validator->errors();
return response()->json($errors->all());
}
and it return error like below :
[
"The prog code field is required.",
"The payer id field is required.",
]
but the problem is how I map the error of which field because I want to show the error below the particular text field.
Can we customize error like below :
[
[prog_code] => "The prog code field is required.",
[payer_id] => "The payer id field is required.",
]
The way I achieve the same response was to do:
if ( $validator->fails() ) {
$errors = [];
foreach ( $validator->errors()->toArray() as $field => $message ) {
$errors[$field] = $message[0];
}
return response()->json($errors);
}
If you dump the $errors variable you have an array of errors like your target:
ViewErrorBag {#406
#bags: array:1 [
"default" => MessageBag {#407
#messages: array:1 [
"pin" => array:1 [
0 => "The Programming Code is required Sir!"
]
]
#format: ":message"
}
]
}
$errors variable is injected by validator when there are errors