In Laravel, how do I do validation to check if checkbox is checked and text input is not empty.
For example:
If checkbox is ticked
<input type="checkbox" name="has_login" checked="checked" value="1">
and pin is not empty then validation should be passed.
<input type="text" name="pin" value="">
In Request file file:
public function rules()
{
return [
'has_login' => ??,
];
}
You should try this way:
public function rules()
{
return [
'has_login' => 'accepted',
'pin' => 'required',
];
}
Related
I have created the form and created multiple fields.
<input name="members[]" type="text" class="form-control">
<input name="members[]" type="text" class="form-control">
<input name="members[]" type="text" class="form-control">
set the validation from the Form Request for the input fields
public function rules()
{
return [
'password' => 'required|max:30',
'members.*' => 'required|max:12',
];
}
How can we check the members' field value exists in the database using the validation?
For password using like this
'password' => ['required', function ($attribute, $value, $fail) {
if (!\Hash::check($value, $this->user()->password)) {
$fail('Old Password did not match to our records.');
}
}],
You want to use the exists validation rule.
Just extend your existing validation rules for members:
'members.*' => 'required|max:12|exists:{phone number table},{phone nummber column}',
The following is my blade :
<form action="{{route('ans1.eval')}}" method="post">
<br>
<input type="radio" name="evaluate" class="evaluate" value=10> 1
<input type="radio" name="evaluate" class="evaluate" value=15> 1.5
<input type="radio" name="evaluate" class="evaluate" value=20> 2
<input type="radio" name="evaluate" class="evaluate" value=25> 2.5
<input type="radio" name="evaluate" class="evaluate" value=30> 3
<button type="submit" class="btn btn-primary" align="right">Evaluate Answer</button>
<input type="hidden" value="{{ Session::token() }}" name="_token">
</form>
The following is my route :
Route::post('/evaluateans', [
'uses' => 'AnswerController#postEvaluateAns',
'as' => 'ans1.eval',
'middleware' => 'auth'
]);
The following is my validation :
public function postEvaluateAns(Request $request)
{
$this->validate($request, [
'evaluate' => 'required'
]);
}
The following is the error when no evaluation is selected :
MethodNotAllowedHttpException in RouteCollection.php line 218
From the laravel docs on validation
If the validation rules pass, your code will keep executing normally;
however, if validation fails, an exception will be thrown and the
proper error response will automatically be sent back to the user. In
the case of a traditional HTTP request, a redirect response will be
generated.
When your validation fails it redirects back with a GET method (a redirection uses the GET method) but if you show the form from a route that is not a GET one it throws this error.
So you have to show the form with a GET route.
As alternative you can manually create your validator so you can choose the redirect GET route in case of failed validation, e.g.:
public function postEvaluateAns(Request $request)
{
$validator = Validator::make($request->all(), [
'evaluate' => 'required'
]);
if ($validator->fails()) {
return redirect('failed_validation_GET_route')
->withErrors($validator)
->withInput();
}
return redirect()->route('success_GET_route')
->with('status', 'Success!');
}
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'patente' cannot be null (SQL: insert into cars (patente, marca, modelo, color, fecha_ingreso, updated_at, created_at) values (?, ?, ?, ?, ?, 2019-06-10 16:27:35, 2019-06-10 16:27:35)
Route::match(['get', 'post'], '/crear',[
'uses'=>'CarController#crear',
'as'=>'cars.crear'
]);
Short code to form
<div class="row">
<div class="col-md-6"></div>
<form action="{{route('cars.crear')}}" method="post">
#csrf
<div class="row form-group">
<div class="col-md-12">
<label for="true">Patente:</label>
<input type="text" name="patente" size="6" maxlength="6" class="form-control" required>
</div>
</div>
code create and show
public function crear(Request $request){
$patente=$request['patente'];
$marca=$request['marca'];
$modelo=$request['modelo'];
$color=$request['color'];
$fecha_ingreso=$request['fecha_ingreso'];
$car=new Car();
$car->patente=$patente;
$car->marca=$marca;
$car->modelo=$modelo;
$car->color=$color;
$car->fecha_ingreso=$fecha_ingreso;
$car->save();
return redirect()->back();
}
public function show(){
$cars=Car::all();
return view ('lista',['cars'=>$cars]);
}
CarController.php
public function crear(Request $request){
request()->validate([
'patente' => 'required',
'marca' => 'required',
'modelo' => 'required',
'color' => 'required',
'fecha_ingreso' => 'required',
'patente' => 'required',
'marca' => 'required',
'modelo' => 'required',
'color' => 'required',
'fecha_ingreso' => 'required'
]);
$car = Car::create([
patente => $request->patente,
marca => $request->marca,
modelo => $request->modelo,
color => $request->color,
fecha_ingreso => $request->fecha_ingreso
]);
return redirect()->back();
}
Your code looks fine, a bit verbose, so I cleaned it up a bit and added validation. The only other thing I can think to suggest is ensure your Car model has the fields added to the protected $fillable array.
Just Validate Your data before store it,
php artisan make:request ClearRequest
in App\Requests\ClearRequest,
class ClearRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'patente'=>'required',
'marca'=>'required',
'modelo'=>'required',
'color'=>'required',
'fecha_ingreso'=>'required',
'patente'=>'required',
'marca'=>'required',
'modelo'=>'required',
'color'=>'required',
'fecha_ingreso'=>'required'
];
}
}
in your controller
use App\Http\Requests\ClearRequest;
in your clear method
public function crear(ClearRequest $request){
...
}
in your view file sth like this,
<form action="/clear" method="POST">
#csrf
patente<br>
<input type="text" name="patente">
<br>
marca<br>
<input type="text" name="marca">
<br>
modelo<br>
<input type="text" name="modelo">
<br>
fecha_ingreso<br>
<input type="text" name="fecha_ingreso">
<br>
patente<br>
<input type="text" name="patente">
<br>
modelo<br>
<input type="text" name="modelo">
<br>
color<br>
<input type="text" name="color">
<br>
fecha_ingreso<br>
<input type="text" name="fecha_ingreso">
<br>
<input type="submit" value="Submit">
</form>
if it is helpful yor you upvote me :)
You are trying to store a null value in a NOT NULL column. Make sure you are passing patente correctly in the request.
I used 5.4 and I've an index action in convert controller which shows the form and then have another action calculate in the convert controller. So the form has from-currency, amount, to-currency input and all of them are required.
Here's the validation I've for calculate action:
$this->validate(request(), [
'from_currency' => 'required|min:3|max:3|alpha',
'to_currency' => 'required|min:3|max:3|alpha',
'amount' => 'required|numeric',
]);
If the validation failed I want when showing the errors and the form it will prepopulate the input already.
Is there like a function I can use for Request ? I know how to get the domain/path inside blade like Request::root() and I also tried Request::input('from_currency) in the view but not work.
I even tried to set the view data like 'from_currency' => request('from_currency') and it's blank. Any idea?
When you are validating your form your request if it fail you can redirect to the same page with all the input which was submited
$validator = Validator::make($request->all(), [
'from_currency' => 'required|min:3|max:3|alpha',
'to_currency' => 'required|min:3|max:3|alpha',
'amount' => 'required|numeric',
]);
if ($validator->fails()) {
return redirect('index')
->withErrors($validator)
->withInput();
}
and in your blade view you can show the old value by ussing the old helper like this
<input type="text" name="from_currency" value="{{ old('from_currency') }}">
<input type="text" name="to_currency" value="{{ old('to_currency') }}">
<input type="text" name="amount" value="{{ old('amount') }}">
Try this
In your blade file, make sure your inputs have this:
<input type="text" ... value="{{ old('from_currency') }}" ... >.
Then in your controller...
if($validation->fails()) {
return redirect()->back()->withInput();
}
You can also user Validate instead of Validator::make.
eg
$this->validate($request, [
'question' => "required|min:10|max:100",
'answer' => "required|min:20|max:300",
'rank' => "required|numeric|gt:0|lt:100",
]);
Then in your form use
<input type="text" class="form-control" id="question" name="question" value="{{ old('question') }}">
This will automatically redirect back with input if the validator fails.
This way, you DO NOT have to include
if($validation->fails()) {
return redirect()->back()->withInput();
}
I have a form using cloneya jQuery plugin to clone form elements. The elements that will be cloned looks like so:
<div class="form-group">
<label for="name">Item name</label>
<input class="form-control" name="name[]" type="text">
</div>
<div class="form-group">
<label for="count">Item count</label>
<input class="form-control" name="count[]" type="text">
</div>
As you can see, each input will be an array instead of string. I want to validate those using Laravel Form Request. Here's my rules:
public function rules()
{
return [
'name' => 'required|between:3,50',
'count' => 'required|integer|min:1',
];
}
But that's not working. When I submitted the form, I got the following error message:
htmlentities() expects parameter 1 to be string, array given
I've been searching for solution, but can't find the appropriate one. Any suggestion would be appreciated!
Basically, in your rules() method, you need to determine how many name and count elements there are in the POST and then create rules for each of them:
public function rules()
{
$rules = [];
foreach ($this->request->get('name') as $index => $val) {
$rules['name.' . $index] = 'required|between:3,50';
}
foreach ($this->request->get('count') as $index => $val) {
$rules['count.' . $index] = 'required|integer|min:1';
}
return $rules;
}
Please check this post.