my validation is working correctly. but didn't show any message. I mention the below.
in controller
$fields = collect([
'monthly_fees',
'admission',
'due_advance',
'session_fee',
'library',
'sports',
'poor_funds',
'fine',
'reciept',
'milad',
'scout',
'development',
'registration',
'f_tutorial',
's_tutorial',
't_tutorial',
'f_exam',
's_exam',
't_exam',
'labratory',
'transport',
'syllabus',
'certificate',
'testimonial',
'generator',
'extra'
]);
$rules = $fields->mapWithKeys(function ($field) use ($fields) {
return [
$field => 'required_without_all:' . $fields->reject(function ($item) use ($field) {
return $item == $field;
})->implode(',')
];
})->toArray();
$this->validate($request, $rules);
in views
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul class="text-center">
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
I also use these lines of codes in the controller but didn't work.
if($this->validate()->fails()) {
return redirect()->back()->with('error','Please Input minimum 1 field...');
}
I want to do minimum 1 field is required. I have 26 input fields. I always use these codes for single use. but this time want to validate minimum One field required. These codes validate the required but didn't show any messages though I mentioned the errors in blade. can you please help me with these errors? thanks in advance.
I solved my problems. here i used $this->vatidate(...);
it was wrong for me. then I used Validator package and returns a custom message with redirect if fails. then it works.
Related
I am using Laravel Framework 8.62.0.
I am validating a form the following way:
$validator = Validator::make($request->all(), [
'title_field' => 'required|min:3|max:100',
'comment_textarea' => 'max:800',
'front_image' => 'required|mimes:jpg,jpeg,png,bmp,tif',
'back_image' => 'required|mimes:jpg,jpeg,png,bmp,tif',
'price' => "required|numeric|gt:0",
'sticker_numb' => "required|numeric|gt:0",
'terms-checkbox' => "accepted",
]);
if ($validator->fails()) {
// Ooops.. something went wrong
return Redirect::back()->withInput();//->withErrors($this->messageBag);
}
I want to display errors in the frontend the following way:
#if ($errors->any())
<div class="alert alert-danger alert-dismissable margin5">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>Errors:</strong> Please check below for errors
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
However, my $error variable is emtpy, when validation errors exist, so the validation errors do not get shown in my frontend.
Any suggestions what I am doing wrong?
I appreciate your replies!
You should pass the $validator to withErrors like:
if ($validator->fails()) {
// Ooops.. something went wrong
return Redirect::back()->withErrors($validator)->withInput();
}
That's because your not passing errors.
Try this:
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
}
As the previous speakers said, you must of course return the errors. but you can also use the Request Validate Helper. it does this automatically.
$request->validate([...])
As soon as an error occurs, it returns a response with the errors.
https://laravel.com/docs/8.x/validation#quick-writing-the-validation-logic
Laravel 5.4 version
The validate() function works until I test more than 3 errors in the form. Upon automatic redirect after buildfailedvalidationresponse function, the 4 $error messages aren't present on and neither is the old form data. This only doesn't work in chrome. Firefox/internet explorer is fine. I have data dumped throughout the process of validatesrequest file and it shows the $error variables being passed correctly to the buildfailedvalidationresponse function but no errors/old form data are presented after redirect. I was just wondering if anybody has had an issue like this with different browsers.
validation method
protected function validateRegistration(Request $request) {
$rules = array(
'name' => 'required|string',
'email' => array('required','string','email','unique:users,email'),
'phone' => 'required|digits:10',
'userid' => array('required','string','min:6','max:10','unique:users,userid','regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$/'),
'password' => array('required','string','min:8','max:12','regex:/^(?
=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$/'),
'repeatedpassword' => 'required|string|same:password',
'code' => 'required|digits:4|exists:codes,code'
);
$this->validate($request, $rules);
if ($this) {
$store = new User();
return $store->insertuser();
}
}
blade validation display errors statement
<div class="container">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li> {{ $error }} </li>
#endforeach
</ul>
</div>
#endif
</div>
I manually created a Validator, but i can't find a method to get the validated data.
For Request, validated data return from $request->validate([...])
For FormRequest, it's return from $formRequest->validated()
But with Validator, i don't see a method like those 2 above.
Assuming that you're using Validator facade:
use Illuminate\Support\Facades\Validator;
$validator = Validator::make($request->all(), $rules, $messages, $attributes);
if ($validator->fails()) {
return $validator->errors();
}
//If validation passes, return valid fields
return $validator->valid();
https://laravel.com/api/5.5/Illuminate/Validation/Validator.html#method_valid
If you use the Validator facade with make it will return a validator instance. This validator instance has methods like validate(), fails() and so on. You can look those methods up in the validator class or in the laravel api-documentation.
Writing The Validation Logic
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
// The blog post is valid...
}
Displaying The Validation Errors
<!-- /resources/views/post/create.blade.php -->
<h1>Create Post</h1>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<!-- Create Post Form -->
View code:
<input type="file" name="queryfile" id="queryfile" required>
Here I am trying to upload the file with .sql extension.
Controller code:
public function debinsert1(Request $request)
{
$validator = Validator::make(Input::all(),
array(
'devicemodel' => 'exists:addProduct,productId',
'debfile' => 'mimes:deb',
'basefile' => 'mimes:deb',
'versions' => 'unique:MainHaghway',
**'queryfile' => 'mimes:sql',**
));
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
}
else{
$temp = new debModel;
if(Input::hasFile('queryfile')){
$file=$request->file('queryfile');
$file->move(public_path().'/downloads',$file-
>getClientOriginalName());
$temp->queryfile=$file->getClientOriginalName();
}
$temp->save();
In this controller code, I am trying to validate with the sql extension and if it succeeds need to insert into db. Validations for other files were working here but, .sql file is not passing with the validation.
Same view code(ie.,mentioned above):
#if (count($errors) > 0)
<div class = "alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Here ,I am throwing the errors incase of failing validations.
This will not validate the sql file as laravel MIME type check here but .sql file don't have MIME type that why its not working but you can do this with manual check by use of php function pathinfo().
Just like this
if(pathinfo($request->queryfile->getClientOriginalName(), PATHINFO_EXTENSION)!=='sql'){
echo 'invalid sql file';
}
I thing it will help you.
I have a validator, it has error messages, and my goal is to get only error messages with the field names.
$validator = Validator::make(
array(
'firstField' => Input::get('firstFieldName');
'secondField' => Input::get('secondFieldName');
),
array(
'firstField' => 'required';
'secondField' => 'required';
)
);
if($validator->fails()){
return $validator->messages();
}
So, this piece of code is returning some values to my js file as following
function getErrorMessages(){
//Some UI functions
var myDiv = document.getElementById('messageDivID');
$.post('validationRoute', function(returedValidatorMessageData)){
for(var a in returedValidatorMessageData){
myDiv.innerHTML = myDiv.value + a;
}
}
}
Problem is, the only values i get from post request is like firstField secondField but i'd like to get like firstField is required message. What would be the easiest way ?
Thanks in advance.
Laravel's messages() method returns array with this format:
[
"first_name" => [
"First name is required."
]
]
Where keys are name of the field and values are arrays of error messages. So just modify your js using values instead of keys. Example:
for (var key in returedValidatorMessageData){
console.log(returedValidatorMessageData[key]);
}
It's not a perfect approach i know, but created my own way as the answer :
if($validator->fails()){
//get all the messages
$errorArray = $validator->errors()->all(':message');
//& operator means changes will affect $errorArray
foreach($errorArray as &$a){
$a = ucfirst($a); //uppercases first letter (you can do this in laravel config too)
$a = '<li>'.$a.'</li>'; //add to list
}
//add a string at the beginning of error message
array_unshift($errorArray, '<p><b>The error messages are following :</b></p>');
//implode and return the value
return implode(' ',$errorArray);
}
You should search in laravel official documentation... in the view use this
<!-- /resources/views/post/create.blade.php -->
<h1>Create Post</h1>
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<!-- Create Post Form -->
in controller :
public function name(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
}