Laravel 6 custom validation

Asked

Viewed 175 times

-1

Hi, guys! I’m new in Laravel and wanted to ask a question about the validations.

This is my controller. When I call the Validator, i am passing the arrays to Rules, messages and Attributes.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpFoundation\Response;
use App\Validators\ContatoValidator;
use App\Models\Contato;

class FaleConoscoController extends Controller
{
    private $app;

    public function __construct(){
        $this->app= App::getFacadeRoot();
    }

    public function send(Request $request){
        $validator = Validator::make($request->all(), ContatoValidator::rules, ContatoValidator::messages, ContatoValidator::attributes);

        if ($validator->fails()) {
            return response() -> json($validator->errors(), Response::HTTP_BAD_REQUEST);
        }else{
            //$model = 
        }
    }
}

Below my class Contactovalidator with arrays:

namespace App\Validators;

class ContatoValidator{

        const rules = [
            'mensagem' => 'required|max:500',
            'assunto' => 'required|max:255',
            'remetente.nome' => 'required|max:255',
            'remetente.email' => 'required|max:255|email',
            'remetente.estado' => 'nullable|max:255',
            'remetente.cidade' => 'nullable|max:255',
        ];

        const messages = [
            'required'=> 'O campo :attribute não foi preenchido',
            'same'    => 'The :attribute and :other must match.',
            'max'     => 'O campo :attribute deve ter no máximo :max caracteres.',
            'between' => 'The :attribute value :input is not between :min - :max.',
            'in'      => 'The :attribute must be one of the following types: :values',
            'email'   => 'O e-mail inserido não é válido.'
        ];

        const attributes = [
            'remetente' => [
                'nome' => 'nome',
                'email' => 'email',
                'estado' => 'estado',
                'cidade' => 'cidade',
            ],
        ];

    }

I want to remetente.nome return as only nome. And so on in the other sender attributes.

However, the result is as follows::

{
    "assunto": [
        "O campo assunto não foi preenchido"
    ],
    "remetente.nome": [
        "O campo remetente.nome não foi preenchido"
    ],
    "remetente.email": [
        "O campo remetente.email não foi preenchido"
    ]
}
  • If you can post your form?

  • I did not make form, I am making the requisition via Postman:

  • {
 "remetente": {
 "email": "",
 "cidade": "Vitória",
 "estado": "Espírito Santo"
 
 },
 "assunto": "",
 "mensagem": "Mensagem enviada por e-mail"
}

  • is that there is difference when it is by form, I will put my answer that is right

  • You need to read this: https://answall.com/help/whats-reputation

  • Also good to read: https://answall.com/help/minimal-reproducible-example

Show 1 more comment

1 answer

0

As explained in the documentation in the item Customization of Messages Errors need to make the following settings as described in your question which in case is for a rest (if it’s form in place of the point is a _, have to be very careful), example:

namespace App\Validators;

class ContatoValidator{

    const rules = [
        'mensagem' => 'required|max:500',
        'assunto' => 'required|max:255',
        'remetente.nome' => 'required|max:255',
        'remetente.email' => 'required|max:255|email',
        'remetente.estado' => 'nullable|max:255',
        'remetente.cidade' => 'nullable|max:255',
    ];

    const messages = [
        'remetente.nome.required'=> 'O campo nome não foi preenchido',
        'remetente.nome.max'=> 'O campo nome tem que ter no máximo', // etc ...
    ];

    const attributes = [
        'remetente' => [
            'nome' => 'nome',
            'email' => 'email',
            'estado' => 'estado',
            'cidade' => 'cidade',
        ],
    ];

}

ie, put the name of the field and the type of validation and enter the message as explained in the example:

'remetente.nome.required'=> 'O campo nome não foi preenchido'

for each validation this should be repeated.

  • So you can’t use the generalized message by customizing the attributes as much as you need to reference an object?

  • This way of doing I had getting, but there was a lot of message equal. Later I found that there is how to make the message referencing the attribute

  • @Anacarol is how it should be done since you want to customize...

  • I wanted to do something like this: https://laracasts.com/discuss/channels/requests/validation-nested-attributes-and-nice-names

  • What you posted has nothing to do, what my reply gives you is the clear example of how to solve, including I have to put in the answer that this works for web api ...

  • This one https://stackoverflow.com/questions/32761230/how-to-set-custom-attribute-labels-for-nested-inputs-in-laravel

  • The way you showed it is a array information and in your case is an object ... is different because it has to be done as I showed you... @Anacarol A thing also is not as you want it is as the framework requires!

  • Well, then you can’t reference the attribute in the message in these cases. You have to write one for each.

  • @Anacarol as your example of the question is what I put as an answer, so it’s an object if it’s array could use this: https://stackoverflow.com/questions/34393279/nested-array-validation-laravel but, it’s not !!! understood ... you have to put as I explained to you in the answer

  • Another example with object: https://laracasts.com/discuss/channels/laravel/validating-nested-json?page=1 @Anacarol

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.