I am trying to validate the form using this way:
// Start validation
$validator = Validator::make($request->all(), [
'project_token' => 'required',
'user_id' => 'required',
'competitor_name' => 'required',
'competitor_domain' => ['required','regex:/^(?!(www|http|https)\.)\w (\.\w ) $/'],
'status' => 'required',
]);
// If validation is not sucessfull
if( $validator->fails() ) {
return response()->json([
'success' => false,
'message' => $validator->withErrors($validator)
], 200);
} else {
....
}
If the validation is failed I want to get the error messages in the message
key. How can I get the error messages ? Its showing me an error message:
Method Illuminate\Validation\Validator::withErrors does not exist.
CodePudding user response:
You have to use a validator error like this
if( $validator->fails() ) {
return response()->json([
'success' => false,
'message' => $validator->errors()
], 200);
}
Or
$validator->errors()->all(); # as a Array
CodePudding user response:
Try this, It will return proper validation message and check the validation on defined field.
$request->validate([
'project_token' => 'required',
'user_id' => 'required',
'competitor_name' => 'required',
'competitor_domain' => ['required','regex:/^(?!(www|http|https)\.)\w (\.\w ) $/'],
'status' => 'required',
], [
'project_token.required' => 'Please Generate Project token'
]);
in your blade file if you add this condition after each element then if any validation error acure then it will show in front with custom message
@if ($errors->has('project_token'))
<span >{{ $errors->first('project_token') }}</span>
@endif
CodePudding user response:
$validator = Validator::make($request->all(), [
'project_token' => 'required',
'user_id' => 'required',
'competitor_name' => 'required',
'competitor_domain' => ['required','regex:/^(?!(www|http|https)\.)\w (\.\w ) $/'],
'status' => 'required',
]);
if( $validator->fails() ) {
return response()->json([
'success' => false,
'message' => $validator->errors()
], 200);
} else {
....
}