1 month ago

Applying additional form validation rules to selectively required fields

Posted 1 month ago by grozavule

I have a form that only requires that one field be complete; it doesn't matter which one. If the field has a value, I would like that value to meet other criteria. Here is the form:

<form action="{{ route('reports.customerordersearch') }}" method="get">
                <div class="form-group">
                    <label class="form-label" for="customer_id">CUSTOMER:</label>
                    <div class="alert alert-danger" role="alert">{{ $message }}</div>
                    <select class="custom-select" name="customer_id">
                        <option value="" selected>Select a customer</option>
                        @foreach($customers as $customer)
                        <option value="{{ $customer->ID }}">{{ $customer->NAME }}</option>
                <div class="form-group">
                    <label class="form-label" for="order-number">CUSTOMER ORDER NUMBER:</label>
                    <div class="alert alert-danger" role="alert">{{ $message }}</div>
                    <input type="text" name="order_number" class="form-control{{ $errors->has('order-number') ? ' is-invalid' : ''}}" value="{{ old('order-number') }}" placeholder="Enter a customer order number to search for" />
                <div class="form-group">
                    <label class="form-label" for="order_status">ORDER STATUS:</label>
                    <div class="alert alert-danger" role="alert">{{ $message }}</div>
                    <select class="custom-select" name="order_status">
                        <option value="U" selected>Select an order status</option>
                        <option value="R">Released</option>
                        <option value="C">Closed</option>
                        <option value="H">On hold</option>
                        <option value="X">Cancelled/Void</option>
                <input class="btn btn-primary" type="submit" name="submit" value="Search" />

Here are the validation requirements:

$validStatuses = array_keys(self::CUSTOMER_ORDER_STATUS);
            $validInput = $request->validate([
                'customer_id' => ['bail', 'required_without_all:order_number,order_status', 'alpha_num'],
                'order_number' => ['bail', 'required_without_all:customer_id,order_status', 'string'],
                'order_status' => ['bail', 'required_without_all:order_number,customer_id', Rule::in($validStatuses)]

If I only fill out Order Status, the Customer field complains that its value, which is intentionally left blank, is not alphanumeric. I would like its alphanumeric requirement to only apply if the field has a value. How can I do that?

Please sign in or create an account to participate in this conversation.