I have the following situation: I have a form and in it I have a field that I need to validate if two other fields are true.
For example, I have the holder_name field, I need this field to be mandatory if a radio type field called paymentMethod is equal to credit_car and if another radio called card is equal to n_card
I tried to do it like this:
'paymentMethod' => 'required|credit_card',
'holder_name.*' => 'required_if:paymentMethod,credit_card',
'card' => 'required|card',
'holder_name.*' => 'required_if:card,n_card',
and so too
"holder_name" => 'required_if:paymentMethod,==,credit_card|required_if:card,==,n_card',
But I was not successful. Can anyone give me a light?? Thanks
You can use custom validation like :
"holder_name" => 'required , function($request) {
return ( $request->paymentMethod == $request->credit_card
&& $request->card == $request-> n_card) }',
Take a look at conditionally-adding-rules
You can use Custom rule for required if
holder_name.*' => Rule::requiredIf(function () {
if(somecondition){
return false;
}
return true;
}),
This method must return true or false
For ref:https://laravel.com/docs/8.x/validation#rule-required-if
Rule::requiredIf(function () {
if($this->paymentMethod==$this->credit_card && $this->card==n_card){
return true;
}
return false;
}),
If you are not using FormRequest then
Rule::requiredIf(function ()use($request) {
if($request->paymentMethod==$request->credit_card && $request->card==n_card){
return true;
}
return false;
}),
the way it worked for me was:
return Validator::make($data, [
'holder_name' => Rule::requiredIf($data['paymentMethod'] == 'credit_card'
&& $data['card'] == 'n_card')],$messages);
Tank's
Related
I am creating a tag factory, and I want to it to either generate a project_tag_id or a gobal_tag_id but not both
return [
'project_card_id' => ProjectCard::inRandomOrder()->first()->id,
'user_id' => User::inRandomOrder()->first()->id,
// to genreate project_tag_id or global_tag_id but not both
'project_tag_id' => ProjectTag::inRandomOrder()->first()->id,
'global_tag_id' => $this->faker->numberBetween(1,5),
];
Any help or insight on this would be much appreciated
Call a Random function if rand function return even insert project_tag_id else return global_tag_id
so,
$number=rand(0,10);
if($number % 2 == 0){
arr['project_tag_id'] => ProjectTag::inRandomOrder()->first()->id;
arr['global_tag_id'] => null;
}else{
arr['project_tag_id'] => null;
arr['global_tag_id'] => $this->faker->numberBetween(1,5);
}
How can I set "array_filter" to accept the null values, empty and zero?
I tried the callback function but it didn't work for me.
Here's my code
$student = array_filter($request->student);
$teacher = array_filter($request->teacher);
$ScID = array_map(null, $student, $teacher);
SchoolDescriptions::where('pin_id', $request->session()->get('pin_id'))->delete();
foreach ($ScID as $key=>$array) {
SchoolDescriptions::updateOrCreate([
'student' => $array[0],
'teacher' => $array[1],
'pin_id' => $request->session()->get('pin_id')
]);
}; return back()->withStatus(__('Successfully saved.'));
I was able to find a solution for this. So I just simply made a condition.
To accept null values when submitting teacher and student forms.
if ($request->student == null && $request->teacher == null)
{
//do nothing
}
else {
$student = array_filter($request->student);
$teacher = array_filter($request->teacher);
$ScID = array_map($student, $teacher);
SchoolDescriptions::where('pin_id', $request->session()->get('pin_id'))->delete();
foreach ($ScID as $key=>$array) {
SchoolDescriptions::updateOrCreate([
'student' => $array[0],
'teacher' => $array[1],
'pin_id' => $request->session()->get('pin_id')
]);
};
}
I want to make start_po_no validation(required_if and digits_between) when po_type value is 1 and use_spo field value is 1.
Now, I'm written validation rule in request file like following:
public function rules()
{
return [
'use_spo' => 'required',
'po_type' => 'required',
'start_po_no' => Rule::requiredIf(function () use ($supplierPoUse, $generatePo) {
return request("use_spo") == 1 && request("po_type") == 1;
}).'|digits_between:1,9',
];
}
But, this code only correct for required_if, but digits_between is still not working. I read laravel validation documentation but I'm not user how to check it correctly.
#Edit
But, digits_between validation still checking even use_spo or po_type is not 1. I want also digits_between validation when use_spo and po_type is equal to 1.
Based on the explanation, I believe you can just add the rules conditionally. No reason to make it more complicated.
public function rules()
{
$rules = [
'use_spo' => 'required',
'po_type' => 'required',
];
if (request("use_spo") == 1 && request("po_type") == 1) {
$rules['start_po_no'] = 'required|digits_between:1,9';
}
return $rules;
}
I have two ways of doing it
Using Closures
return [
'use_spo' => 'required',
'po_type' => 'required',
'start_po_no' => [
Rule::requiredIf(function () use ($supplierPoUse, $generatePo) {
return request("use_spo") == 1 && request("po_type") == 1;
}),
function ($attribute, $value, $fail) {
if (request("use_spo") == 1 && request("po_type") == 1) {
if(!(1 <= $value && $value <= 9))
$fail('The '.$attribute.' is invalid.');
}
}
]
];
Using add()
Don't use digits between just after but do it after validation rules are run.
you can add your validation after initial validation.
$validator = Validator::make(...);
$validator->after(function ($validator) {
if (request("use_spo") == 1 && request("po_type") == 1) {
if(!(1 <= $value && $value <= 9))
$validator->errors()->add(
'start_po_no', 'invalid start po no'
);
}
});
if ($validator->fails()) {
// throw your validation exception
}
I need to do a conditional validation on a field: if other_field = 1 then this_field = notBlank. I can not find a way to do this.
My validator in table class:
public function validationDefault(Validator $validator) {
$validator->allowEmpty('inst_name');
$validator->add('inst_name', [
'notEmpty' => [
'rule' => 'checkInstName',
'provider' => 'table',
'message' => 'Please entar a name.'
],
'maxLength' => [
'rule' => ['maxLength', 120],
'message' => 'Name must not exceed 120 character length.'
]
]);
return $validator;
}
public function checkInstName($value, array $context) {
if ($context['data']['named_inst'] == 1) {
if ($value !== '' && $value !== null) {
return true;
} else {
return false;
}
} else {
return true;
}
}
Trouble here is, if i note, in the start of the method, that the field is allowed to be empty, when the entered value is empty, Cake doesn't run through any of my validations, because it's empty and allowed to be such. If i do not note that the field can be empty, Cake just runs "notEmpty" validation before my custom validation and outputs "This field cannot be left empty" at all time when it's empty.
How do i make Cake go through my conditional "notEmpty" validation?
I did try validation rule with 'on' condition with the same results.
Successfully tested, this might help you and others. CakePHP 3.*
$validator->notEmpty('event_date', 'Please enter event date', function ($context) {
if (!empty($context['data']['position'])) {
return $context['data']['position'] == 1; // <-- this means event date cannot be empty if position value is 1
}
});
In this example Event Date cannot be empty if position = 1 . You must put this condition if (!empty($context['data']['position'])) because the $context['data']['position'] value only will exist after the user click submit button. Otherwise you will get notice error.
Columns (both datatype time):
Start
End
End cannot be before start.
$validator
->requirePresence('end', 'create')
->notEmpty('end')
->add('end', [
'time' => [
'rule' => 'time',
'message' => 'end can only accept times.'
],
'dependency' => [
'rule' => [$this, 'endBeforeStart'],
'message' => 'end can not be before start.'
],
]);
If it is a PUT request which only contains end, the model will need to query the existing record to compare against start. If it is a PUT which contains both then it need to validate against the intended new parameter.
How does cakePHP3 do this?
private function endBeforeStart($fieldValueToBeValidated, $dataRelatedToTheValidationProcess)
{
//What goes here?
}
I can't seem to find any examples of doing this online.
I'm not quite sure and haven't tested it, but maybe this gives you some hints:
$validator
->add('end', [
'endBeforeStart' => [
'rule' => function ($value, $context) {
// If it's a POST (new entry):
if ( $context['newRecord'] == '1' ) {
// Do your comparison here
// Input values are e.g. in $context['data']['starttime']
// If end is before start:
return false;
}
// If it's a PUT (update):
else {
// If starttime is not in $context['data']['starttime']
// check for the old value in $getOldEntry
$getOldEntry = $this->getOldEntry( $context['data']['id'] );
// And do your comparison here...
// If end is before start:
return false;
}
return true;
},
'message' => 'end can not be before start.' ],
])
public function getOldEntry($id = null) {
return $this->get($id);
}
I'm also not sure if the last function has to be private or public...