Reputation: 105
I have a form that I want to display only when the checkbox is checked using jQuery. I've also applied Laravel validation in the controller by sending ajax and its working perfectly for me.
$validator = Validator::make($request->all(), [
'shipping_company' => 'required',
'shipping_first_name' => 'required',
'shipping_last_name' => 'required',
'shipping_address' => 'required',
'shipping_address_2' => 'required',
'shipping_city' => 'required',
'shipping_postal_code' => 'required',
'shipping_country' => 'required',
'shipping_state' => 'required',
]);
The form fields are now only visible on the frontend when this specific checkbox is checked.
<div class="form-check tfu-cart-ship-check p-1 my-2 ">
<input class="form-check-input m-1" name="shipping_checkbox" type="checkbox" value="" id="tfu-ship-check">
<label class="form-check-label" for="tfu-ship-check">
<strong> Ship to different address</strong>
</label>
</div>
The validation works fine when the form is submitted, but it applies to both cases, regardless of whether the checkbox is checked or not. I tried using Laravel validation to make it work only when the checkbox is checked, but it’s not working as expected.
I tried this:
$validator = Validator::make($request->all(), [
'shipping_company' => 'sometimes|required',
'shipping_first_name' => 'sometimes|required',
'shipping_last_name' => 'sometimes|required',
'shipping_address' => 'sometimes|required',
'shipping_address_2' => 'sometimes|required',
'shipping_city' => 'sometimes|required',
'shipping_postal_code' => 'sometimes|required',
'shipping_country' => 'sometimes|required',
'shipping_state' => 'sometimes|required',
]);
$validator->sometimes(['shipping_company', 'shipping_first_name', 'shipping_last_name', 'shipping_address', 'shipping_address_2', 'shipping_city', 'shipping_postal_code', 'shipping_country', 'shipping_state'], 'required', function ($input) {
return $input->shipping_checkbox;
});
Can anyone help me out.
Upvotes: 3
Views: 61