Why the validation message are not appearing with required_if? - laravel

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
},

Related

how to use js validator for two different forms in laravel?

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

laravel validation to check multi dimensional array

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.'
];
}

Laravel Valiadtion array must have one element with a certain value

Imaging having the following input for a form request validation.
[
'relations' =>
[
[
'primary' => true,
],
[
'primary' => false,
],
],
],
Is there any validation that makes it possible to secure that at least one of the relations models have primary set to true? More perfect if it could secure only one element is true. This problem seems like it could have existed before.
So if we only see the input for relations, this should pass.
[
'primary' => true,
],
[
'primary' => false,
],
This should fail in validation.
[
'primary' => false,
],
[
'primary' => false,
],
Try an inline custom rule:
public function rules()
{
return [
'relations' => function ($attribute, $relations, $fail) {
$hasPrimary = collect($relations)
->filter(function ($el) {
return $el['primary'];
})
->isNotEmpty();
if ( ! $hasPrimary)
{
$fail($attribute . ' need to have at least one element set as primary.');
}
},
// the rest of your validation rules..
];
}
Of course, you could extract this to a dedicated Rule object, but you get the idea.

Laravel array key validation

I have custom request data:
{
"data": {
"checkThisKeyForExists": [
{
"value": "Array key Validation"
}
]
}
}
And this validation rules:
$rules = [
'data' => ['required','array'],
'data.*' => ['exists:table,id']
];
How I can validate array key using Laravel?
maybe it will helpful for you
$rules = ([
'name' => 'required|string', //your field
'children.*.name' => 'required|string', //your 1st nested field
'children.*.children.*.name => 'required|string' //your 2nd nested field
]);
The right way
This isn't possible in Laravel out of the box, but you can add a new validation rule to validate array keys:
php artisan make:rule KeysIn
The rule should look roughly like the following:
class KeysIn implements Rule
{
public function __construct(protected array $values)
{
}
public function message(): string
{
return ':attribute contains invalid fields';
}
public function passes($attribute, $value): bool
{
// Swap keys with their values in our field list, so we
// get ['foo' => 0, 'bar' => 1] instead of ['foo', 'bar']
$allowedKeys = array_flip($this->values);
// Compare the value's array *keys* with the flipped fields
$unknownKeys = array_diff_key($value, $allowedKeys);
// The validation only passes if there are no unknown keys
return count($unknownKeys) === 0;
}
}
You can use this rule like so:
$rules = [
'data' => ['required','array', new KeysIn(['foo', 'bar'])],
'data.*' => ['exists:table,id']
];
The quick way
If you only need to do this once, you can do it the quick-and-dirty way, too:
$rules = [
'data' => [
'required',
'array',
fn(attribute, $value, $fail) => count(array_diff_key($value, $array_flip([
'foo',
'bar'
]))) > 0 ? $fail("{$attribute} contains invalid fields") : null
],
'data.*' => ['exists:table,id']
];
I think this is what you are looking:
$rules = [
'data.checkThisKeyForExists.value' => ['exists:table,id']
];

How to get common validation error message for array field

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

Resources