1

I wanted to ask for your help about how I can add validation to forms if routes are used rather than controllers. The code I use so far:

Route::post('/contact/submit', function (Request $request) {
    validate($request,[
        'FirstName'=>'required',
        'LastName'=>'required',
        'Age'=>'required'
    ]);

Also, how is it possible to add custom validation, for example, to ensure that instead of message "Name is required" just show "Please fill name field".

1 Answer 1

3

Yes you need to use Validator class and yes you can also add another variable for custom message.

Route::post('/contact/submit', function (Illuminate\Http\Request $request) {
    $rules = [
        'FirstName' => 'required',
        'LastName' => 'required',
    ];
    $messages = [
        "FirstName.required" => "First name is compulsory.",
        "LastName.required" => "Last name is mandadory.",
    ];
    $validator = Validator::make($request->all(), $rules,$messages);
    if($validator->fails()){
        return dd($validator->messages());
    }
});

Error Message will be like

MessageBag {#1332 ▼
  #messages: array:2 [▼
    "FirstName" => array:1 [▼
      0 => "First name is compulsory."
    ]
    "LastName" => array:1 [▼
      0 => "Last name is mandadory."
    ]
  ]
  #format: ":message"
}
Sign up to request clarification or add additional context in comments.

2 Comments

@2486, thank you for your solution, so Validator is used with route i and validate is used with controller. Right? I hope for your answer
you can also use $request->validate function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.