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
}
Related
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
I have the following validation requirement.
if inventory_purchase_bill == True, lines..sku should be
required|exists:items,sku if inventory_purchase_bill == False,
lines..sku should be nullable|exists:items,sku
Basically test for exists only if there is a value. If no value or null then, don't check for exists.
Tried following, but second-line overrides first. How to achieve this?
$validation = $this->validate($request, [
'inventory_purchase_bill' => 'required',
'lines.*.sku' => 'exclude_unless:inventory_purchase_bill,false|nullable|exists:items,sku',
'lines.*.sku' => 'exclude_unless:inventory_purchase_bill,true|required|exists:items,sku',
]);
'lines.*.sku' => function($attribute, $value, $fail) use ($request) {
if ($request->bill_type == 'Stock Purchase') {
if($value !=null && $value != ''){
$item = Item::where('sku',$value)->first();
if($item == null){
return $fail($value.' not in database. Please add new item.');
}
}else{
return $fail('SKU is required.');
}
}
if ($request->bill_type == 'Expense') {
if($value !=null && $value != ''){
$item = Item::where('sku',$value)->first();
if($item == null){
return $fail($value.' not in database. Please add new item.');
}
}
}
},
I have a form that accepts delivery of products which I noticed if I enter 0 in the quantity field it doesn't save in the database even if I add data in the calendar or in Notes field.
I already commented out the \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,iin kernel.php still doesn't work.
how can I forced laravel to save my data even if I want to put 0 in quantity? thanks in advance!
update
public function store(Request $request)
{
$input = $request->all();
$items = [];
for ($i = 0; $i <= count($input['order_id']); $i++) {
if (empty($input['stock_in_qty'][$i]) || !is_numeric($input['stock_in_qty'][$i])) continue;
$acceptItem = [
'order_id' => $input['order_id'][$i],
'product_id' => $input['product_id'][$i],
'order_item_id' => $input['order_item_id'][$i],
'delivery_date' => $input['delivery_date'][$i],
'company_id' => $input['company_id'][$i],
// 'stock_in_qty' => intval($input['stock_in_qty'])[$i],
'stock_in_qty' => $input['stock_in_qty'][$i],
// 'stock_out_qty' => $input['stock_out_qty'][$i],
// 'transfer_to' => $input['transfer_to'][$i],
'delivery_note' => $input['delivery_note'][$i],
'user_id' => $input['user_id'][$i],
];
array_push($items, Warehouse1stocks::create($acceptItem));
$stockSummary = Warehouse1StockSummaries::firstOrCreate(
['product_id' => $input['product_id'][$i]],
['qty_in' => $input['stock_in_qty'][$i],
'qty_out' => null,
]);
if (!$stockSummary->wasRecentlyCreated) {
$stockSummary->increment('qty_in', $input['stock_in_qty'][$i]);
}
}
if ($input['rd'] == $input['stock_in_qty'] || $input['rd'] == 0) {
$order_idAcceptedItem = $acceptItem['order_id'];
$setStatus = \App\Orders::where('id', '=', $order_idAcceptedItem)->first();
if ($setStatus) {
$setStatus->status_id = 4;
}
$setStatus->save();
} else {
$order_idAcceptedItem = $acceptItem['order_id'];
$setStatus = \App\Orders::where('id', '=', $order_idAcceptedItem)->first();
if ($setStatus) {
$setStatus->status_id = 3;
}
$setStatus->save();
}
return redirect()->route('orders.index');
}
empty() will return true with 0 or '0' which will mean that if you try to change the quantity to 0 the for loop will just continue on to the next loop. If you need to check if the value exists you can instead use isset().
Changing your first if statement to the following should be all you need:
if(!isset($input['stock_in_qty'][$i]) || !is_numeric($input['stock_in_qty'][$i])) continue;
I'm working on a functionality where only a user with the ID number 3 can bet if the match is 1 minute away from starting, it's a success, but now those matches that has the status "Open" is not allowed to place bets. here is the code:
public function *addMatchBet*(Request $request){
$rules = [
'matchid' => 'required|integer|exists:matches,id',
'teamid' => 'required|integer|exists:teams,id',
'bet_amount' => 'required|integer|min:100'
];
$validation = \**Validator**::make($request->all(), $rules);
if ($validation->passes()) {
$user = \**Auth**::user();
$match = \App\**Match**::find($request->matchid);
$team = \App\**Team**::find($request->teamid);
if(!in_array($team->id, [$match->team_a, $match->team_b])) {
return [
'success' => false,
'errors' => [
'bet' => ['Match teams have been updated! Please refresh
page and try again.']
]
];
}
if($match && $match->status == 'open') {
$betCount = $user->bets
->where('match_id', $request->matchid)
->count();
if($match->isClosing(0)) {
return [
'success' => false,
'errors' => [
'bet' => ['Could no longer bet. This match is now
starting!']
]
];
}
}
}
}
Any ideas anyone? TYIA
I've found a solution, this was the code:
if($match && $match->isClosing(0)) {
if($user->id == 3){
$betCount = $user->bets
->where('match_id', $request->matchid)
->count();
}
else{
return [
'success' => false,
'errors' => [
'bet' => ['Could no longer bet. This match is now starting!']
]
];
}
}
Validation row with others rows in cakephp
i need validate "date range" to save with others "date ranges" values.
Something like this:
function dateNotColision($check) {
foreach($this->data[$this->name] as $row){
if(($row['date_start']>=$date_start && $date_start<=$row['date_end']) ||
($row['date_start']>=$date_end && $date_end<=$row['date_end']) ){
return false;
}
}
return true;
}
how i could?
public function customDateValidation($field) {
return ($this->data[$this->alias]['date_start'] >= $date_start && $this->data[$this->alias]['date_end'] <= $date_start) || ($this->data[$this->alias]['date_start'] >= $date_end && $this->data[$this->alias]['date_end'] <= $date_end)
}
in your validate array just set something like
'start_date' => array(
'rule' => 'customDateValidation',
'message' => 'wrong dates'
)
Finally i did this:
In Model:
public $validate = array(
'date_start' =>array('rule'=>'dateNotColision',
'message' => 'Date Colision'
),
'date_end' =>array('rule'=>'dateNotColision',
'message' => 'Date Colision'
)
);
var $dataArray=array();
public function setDataArray($array){
$this->dataArray=$array;
}
function dateNotColision($check) {
foreach($this->dataArray as $row){
if(($row['date_start']>=$check && $check<=$row['date_end'])){
return false;
}
}
return true;
}
In Controller:
$this->Hotel->Season->setDataArray($this->request->data['Season']);
foreach($this->request->data['Season'] as $reviewData){
$this->Hotel->Season->saveAssociated($reviewData);
}