I have a newly added select box in my laravel update form:
<tr>
<td>{!! Form::label('statusCode', 'Active') !!}</td>
<td>{!! Form::select('statusCode', array('A' => 'Yes', 'D' => 'No')) !!}</td>
</tr>
Setting it to Yes or No works, and when I submit the form it updates the database record properly but there's a bit of headache with validation.
Technically, if I set it to 'No' to deactivate an image then all I need is the id of the image so I know which one to deactivate but right now it forces validation on unnecessary inputs if they're blank.
So on this block, if my select is set to 'D' or 'No' then I only need to require the id:
$this->validate($request, [
'id' => 'required|numeric|unique:jfi.image_files,id,' . $id,
'prdGrpNum' => 'numeric|required',
'altGrpDesc' => 'required',
'cover1' => 'numeric|required',
'color1' => 'numeric|required',
'typeId' => 'numeric|required'
]);
However, this next block I'm checking any filled out inputs against the database to keep data sanitized.
So for this block, I want to say "IF select box is set to 'D'/'No' AND this field is empty, don't validate. Else, do this existing validation for the imageService"
if(!$imageService->validImageTypeId($request->typeId))
return back()->withErrors("Invalid image type given");
How can I use the value of the select box to allow empty fields to skip validation but filled out fields to still be validated?
You can use required_if rule:
required_if:anotherfield,value,...
'prdGrpNum' => 'required_if:statusCode,Yes|numeric'
and the same for the other rules.
Related
I have three forms, and one submit button. I only render two of the forms at any given point based on some predicate but when I submit the form, I would like the validate only the fields that exist in the currently rendered forms
Here is what the validation rules look
public function rules($request) {
return [
'name' => 'required|max:255',
'firm' => 'required|max:255',
'contactnumber' => 'required|numeric',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:'.Spark::minimumPasswordLength(),
'vat_id' => 'nullable|max:50|vat_id',
'terms' => 'required|accepted',
'accountHolderEmail' => 'required|email|max:255',
'accountHolder' => 'required|max:255',
'cardNumber' => 'required|numeric|digits:16',
'cvc' => 'required|numeric|digits:3',
'expiry_month' => array('required', 'regex:/0[1-9]|1[0-2]/'),
'expiry_year' => 'required|numeric|digits:4|date_format:Y|after:'. date('Y', strtotime('-1 years'))
];
}
I would like to validate the last six fields only when I have rendered the form that contains those fields, but I just cannot seem to get it right.
I have tried adding sometimes but that just makes the fields completely optional and that is not the desired behavior because when the form requiring those fields is rendered, we actually need the fields to be mandatory.
I have also tried using Validator::make and passing those last six fields there and that does not do it as well.
You can set flags for each form and set a value for them whether they are rendered or not.
For example
<input name="flag1" value="1"> //if form 1 is rendered
<input name="flag2" value="0"> //if form 2 is not rendered
Then you can use required_if validator like mentioned below:
'name' => 'required_if:flag1,1|max:255',
'firm' => 'required_if:flag2,1|max:255',
$request->validate([
'item'=>'required',
]);
Drop down list
{{Form::select('item', array('','1' => '1', '2' => '2'))}}
I set the first one to '' but it doesn't throw an error that none are selected. It is storing a blank I want the user to select a non blank option
you can set min for validation
$request->validate([
'item'=>'required|integer',
]);
Add min rule:
$request->validate([
'item'=>'required|min:1',
]);
I have a validator for users to update their profile, and on the same page the user can change their password. Although, I do not want to run a check if all the 3 fields (current password, new / confirmed) is empty.
Is there a way I can add in a custom check in the Validator::makeand check, or add to the validator and add the return with errors page?
$validator = Validator::make($request->all(), [
'first_name' => 'required|max:191',
'last_name' => 'required|max:191',
'email' => 'required|email|max:191'
]);
example 3 field are empty and wouldnt be a problem, although what if they're filled out... can I append to this for check
example
if ($request->new_password) {
$validator .= array('new_password' => 'required');
}
my last solution would be to have two validators... would that work?
You can accomplish this by adding sometimes to your rule list. sometimes runs validation checks against a field only if that field is present in the input array. As an exmaple,
$v = Validator::make($data, [
'email' => 'sometimes|required|email',
]);
For more rules options you can refer to Laravel Validator Documentation.
I'm trying to create a user update validation through form, where I pass, for example 'password'=>NULL, or 'password'=>'newone';
I'm trying to make it validate ONLY if it's passed as not null, and nothing, not even 'sometimes' works :/
I'm trying to validate as :
Validator::make(
['test' => null],
['test' => 'sometimes|required|min:6']
)->validate();
But it fails to validate.
Perhaps you were looking for 'nullable'?
'test'=> 'nullable|min:6'
Though the question is a bit old, this is how you should do it. You dont need to struggle so hard, with so much code, on something this simple.
You need to have both nullable and sometimes on the validation rule, like:
$this->validate($request, [
'username' => 'required|unique:login',
'password' => 'sometimes|nullable|between:8,20'
]);
The above will validate only if the field has some value, and ignore if there is none, or if it passes null. This works well.
Do not pass 'required' on validator
Validate like below
$this->validate($request, [
'username' => 'required|unique:login',
'password' => 'between:8,20'
]);
The above validator will accept password only if they are present but should be between 8 and 20
This is what I did in my use case
case 'update':
$rules = [
'protocol_id' => 'required',
'name' => 'required|max:30|unique:tenant.trackers'.',name,' . $id,
'ip'=>'required',
'imei' => 'max:30|unique:tenant.trackers'.',imei,' . $id,
'simcard_no' => 'between:8,15|unique:tenant.trackers'.',simcard_no,' . $id,
'data_retention_period'=>'required|integer'
];
break;
Here the tracker may or may not have sim card number , if present it will be 8 to 15 characters wrong
Update
if you still want to pass hardcoded 'NULL' value then add the
following in validator
$str='NULL';
$rules = [
password => 'required|not_in:'.$str,
];
I think you are looking for filled.
https://laravel.com/docs/5.4/validation#rule-filled
The relevant validation rules are:
required
sometimes
nullable
All have their uses and they can be checked here:
https://laravel.com/docs/5.8/validation#rule-required
if you want validation to always apply
https://laravel.com/docs/5.8/validation#conditionally-adding-rules
if you want to apply validation rules sometimes
https://laravel.com/docs/5.8/validation#a-note-on-optional-fields
if you want your attribute to allow for null as value too
I have a form containing text inputs and select box. I was trying to apply laravel validation. Now i wanted to retain the user inputted values, if validation doesn't success.
I am able to get this done on input box, but not on select box. How to show previously selected value(in select box) if validation doesn't pass.
This is my code
{{Form::select('vehicles_year', $modelYears, '-1', ['id' => 'vehicles_year'])}}
<span class="help-block" id="vehicles_year_error">
#if ($errors->has('vehicles_year')) {{$errors->first('vehicles_year')}} #endif
</span>
-1 is the key of default value that i am showing when the form loads.
What I do is that I add "default" option which value is set to "nothing".
In validation rules I say this value is required. If user does not pick
one of the other options, validation fails.
$options = [
'value' => 'label',
'value' => 'label',
'value' => 'label',
'value' => 'label',
];
$options = array_merge(['' => 'please select'], $options);
{{ Form::select('vehicles_year', $options, Input::old('vehicles_year'), ['id' => 'vehicles_year']) }}
#if ($errors->has('vehicles_year'))
<span class="help-block" id="vehicles_year_error">
{{ $errors->first('vehicles_year') }}
</span>
#endif
// Validation rules somewhere...
$rules = [
...
'vehicles_year' => 'required|...',
...
];
The controller code is missing. I will suppose your handle the POST in a controller method and then you Redirect::back()->withInput();
Thanks to ->withInput() You can use in your view something like Input::old() to get the Input values of your previous request.
So to select your previous item AND have -1 by default, you can use Input::old('vehicles_year', -1)
The first argument is the Input name, and the second is the default value.
{{Form::select('vehicles_year', $modelYears, Input::old('vehicles_year', -1), ['id' => 'vehicles_year'])}}
Hope this helps