Customize Laravel Validator messages for the "sometimes" validation rule

In this snippet of my code, I have implemented form input validation:

public function saveData(Request $request){
    $form_data = $request->all();

    $validation_fields = [
        'first_name' => 'required',
        'last_name' => 'required',
        'cod_fisc' => 'sometimes|required|size:16',
        'p_iva' => 'sometimes|required|between:11,13'
    ];

    $errorMsgs = [
        'first_name.required' => 'Il campo Nome è obbligatorio.',
        'last_name.required' => 'Il campo Cognome/Ragione sociale è obbligatorio.',
        'cod_fisc.required' => 'Il campo Codice Fiscale deve contenere 16 caratteri',
        'p_iva.required' => 'Il campo Partita Iva deve contenere 11 o 13 caratteri',
    ];

    $validator = Validator::make($form_data, $validation_fields, $errorMsgs);

    ....
}

The project is specifically designed for an Italian audience, so all error messages are in Italian. However, I encountered an issue where the custom error messages for the "cod_fisc" and "p_iva" rules were being ignored when using the "sometimes" rule.

What could be the reason behind this?

Answer №1

After conducting a thorough search for your issue, I stumbled upon this helpful resource: https://example.com/solving-custom-validator-challenges

This reference addressed a problem that closely resembled yours. The initial code snippet provided was:

$v = Validator::make(
    $request->all(),
    [ 'first_name' => 'required|max:60'],
    ['first_name.required' => 'First name is really required, yo']
);

$v->sometimes('last_name', 'required|in:fake', function($input){
    return true;
});

The solution presented in the source code consisted of:

$v = Validator::make(
    $request->all(),
    [ 'first_name' => 'required|max:60'],
    ['first_name.required' => 'First name is really required, yo'],
    ['last_name.in' => 'Last name must be fake, too']
);

$v->sometimes('last_name', 'required|in:fake', function($input){
    return true;
});

It seems that by utilizing the sometimes method on the output of Validator::make, you can specify the field name, validator rules, and a boolean condition for validation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create an HTML form that sends email notifications using a third-party form backend platform

I recently designed a form using Webflow and integrated it with Getform.io for the backend platform. Everything is running smoothly, including data collection and file uploads. However, I now want to enhance the form by enabling it to automatically send ...

Notifying with Jquery Alert after looping through routes using foreach loop

I am trying to create a jQuery alert message that displays after clicking on a dynamically generated button in the view using a foreach loop. The issue I am facing is that only the first button in the loop triggers the alert, while the subsequent buttons ...

Create a Bootstrap modal that includes a checkbox option to prevent it from appearing again in

I am attempting to display a bootstrap modal upon body load based on a value retrieved from a MySQL database. The bootstrap modal is included in the body and shown successfully depending on the database value using the following code snippet: $results ...

Unable to submit form with Jquery

Having some trouble with my form submission using Jquery. The submit part of my code seems to be malfunctioning, and I can't pinpoint the issue. <?php if(!isset($_SESSION["useridentity"])){ die(header("Location:index.php")); } ...

Avoiding the storage of POST data in JSON format

Here is some code I am working with: var jsonString = "some string of json"; $.post('proxy.php', { data : jsonString }, function(response) { var print = response; alert(print); }); And this P ...

How can I show search results in a textbox using Codeigniter and Ajax?

After successfully fetching the data from the textbox, I need to display the id in a text input field. I also need to view the data of other fields from the table based on the textbox input. Below is the code snippet containing my View and Ajax implement ...

Unable to display Laravel Vue components in application

Hi there, I'm currently experimenting with Laravel and experiencing an issue where the components I create are not showing up when I run the project. Strangely enough, the example component does appear but any changes I make do not reflect. I followe ...

How can I transform a MySQL query into a Laravel Eloquent query?

I need assistance with retrieving data from two tables: pharmacies and addresses. Currently, I have a query that accomplishes this task: SELECT pharmacies.*, addresses.*, ( 6371 * acos( cos( radians(32.5033801) ) * cos( radians( lat ) ) * co ...

Validating PUT/PATCH requests in Laravel 5.2's REST controller

I'm encountering an issue with Laravel that is resulting in a 405 MethodNotAllowedHttpException error. I've been attempting to implement validation for update requests in my resource PointController, but it seems that the validation rules defined ...

Locate complete words using the strpos() function

Hey there, I’m currently working on using the strpos() function to locate complete words within a sentence. However, I’ve come across an issue where it is also detecting the word if it is just a part of another word. For instance: $mystring = "It&apos ...

Extract all class elements from HTML code and save them to a text file using PHP

Is there a way to extract all span elements with the class "msgsource" from my website's HTML code and then save it as a .txt file for downloading? I tried using the following code, but it only downloads an empty text file: <?php // Grabbing conte ...

Symfony2 - Utilizing an Entity repository to encode data into JSON for efficient AJAX calls

I'm currently working on implementing a dynamic text field with AJAX autocomplete functionality. In order to handle the AJAX call, I have created a method in the controller. public function cityAction(Request $request) { $repository = $this-> ...

Utilizing HTML forms in combination with Google Charts to generate interactive graphs

Recently, I've been working on a project where I'm trying to incorporate Visual Analytics. I'm looking to create a graph from a UI that's part of an HTML form. Below is the code snippet from my HTML page: <!DOCTYPE html> <html& ...

Looping through mysql data horizontally within a div tag

Looking for assistance to create a content loop similar to the one on this website? I attempted to use a while() loop, but it ended up displaying vertically without using a table. I suspect this page utilizes thumbnails. What I aim for is to have the it ...

Is there a way to retrieve the values of a checkbox from a location outside the form where it is initially defined?

After successfully developing a script that deletes rows from a table when a checkbox is selected, I encountered an issue where the values of the checkboxes were not accessible outside of the form action they were placed in. The checkboxes and correspondin ...

Guide to identifying a particular keyword within a vast database of text

I've been grappling with this problem for a day now, focusing on the PHP + MYSQL aspect. However, due to the large amount of data, most of the scripts I've attempted have timed out. Our database consists of two tables: People with approximatel ...

Preserve data across all pages using sessions

On my website, I have a pagination system where each page displays 10 data entries. Whenever a user clicks on the pagination buttons, it triggers a request to the database to fetch the corresponding records. Each data entry also includes a button that can ...

Obtain POST information through AJAX and jQuery

post.js $.post( "/scripts/update.php", {id: testId, age: testAge}, function(data) { $(".testDiv").html(data.testId); $(".testDiv2").html(data.testAge); } ); update.php $userId = $_POST["id"]; $userAge = $_POST["age]; // contact database ...

Adding parameters to a URL is a common practice

"Adding additional information to a URL that was previously included?" I apologize for the confusing title, but I can't find a better way to phrase it. Perhaps an example will make things clearer. Let's say I have URL 1: http://example.com/?v ...

How to Establish a Connection Script: Is Unset the Right Choice?

I came across a helpful article that was teaching me how to create a connection script in PHP. You can find it here: However, I noticed that the article defines the unset function differently in two different places, which has left me feeling confused. Fo ...