0

I am having a form with dynamic input fields that are validated from Laravel 8 and sends back the errors messages as a response.

The problem that I am facing here is the non dynamic form fields are validated as expected but within the dynamic form fields the validation error is put out even if the dynamic input field is filled and the error message is showing under every dynamic input as a result the form is not getting submitted.

here's my laravel validator. Address field is the only dynamic input field which can be added more.

$validator = Validator::make($request->all(), [
        'name' => 'required',
        'code' => 'required',
        'agent_id' => 'required',
        'phone_home' => 'required',
        'phone_work' => 'required',
        'phone_mobile' => 'required',
        'address' => 'required',
    ]);

    if ($validator->fails()) {
        return response()->json([
            'status' => 422,
            'errors' => $validator->messages(),
        ]);

I am using react hooks. here's how my states are added.

const [errorList, setError] = useState([])
const [inputList, setInputList] = useState({
name: '',
code: '',
agent_id: '',
phone_home: '',
phone_work: '',
phone_mobile: '',
address_list: [{ address: '' }],
})

Here where I submit my form and get the errors if the fields are not added.

const submitProductMix = (e) => {
e.preventDefault()
axios.post(`/api/create_customer`, inputList).then((res) => {
  if (res.data.status === 200) {
    swal('Success', res.data.message, 'success')
    setError([])
    history.push('/customers')
  } else if (res.data.status === 422) {
    setError(res.data.errors)
  }
})
}

And here's where I added the dynamic form fields and the error list.

{inputList.address_list.map((items, i) => {
              return (
                <>
                  <div key={i} className="row">
                    <div className="col-lg-8 mb-3">
                      <div className="form-group">
                        <label className="pb-2">
                          Delivery Address <span className="text-danger">*</span>
                        </label>
                        <input
                          className="form-control"
                          type="text"
                          name="address"
                          onChange={(e) => handleChange(e, i)}
                          value={items.address}
                          placeholder="Delivery Address"
                        />
                        <span className="text-danger">{errorList.address}</span>
                      </div>
                    </div>

                    {inputList.address_list.length - 1 === i && (
                      <div className="col-lg-1 mb-2 mt-4 pt-2">
                        <button className="btn btn-success" onClick={handleAddInput}>
                          Add
                        </button>
                      </div>
                    )}

                    {inputList.address_list.length !== 1 && (
                      <div className="col-lg-1 mb-2 mt-4 pt-2">
                        <button
                          className="btn btn-danger"
                          onClick={(e) => handleRemoveInput(e, i)}
                        >
                          Remove
                        </button>
                      </div>
                    )}
                  </div>
                </>
              )
            })}

I have added the entire map along with two button to show how I add or remove the dynamic form fields specifically.

here's my console log

Object { name: (1) […], code: (1) […], agent_id: (1) […], phone_home: (1) […], phone_work: (1) […], phone_mobile: (1) […], address: (1) […] }
​
address: Array [ "The address field is required." ]
​​
0: "The address field is required."
​​
length: 1
​​
<prototype>: Array []
​
agent_id: Array [ "The agent id field is required." ]
​​
0: "The agent id field is required."
​​
length: 1
​​
<prototype>: Array []
​
code: Array [ "The code field is required." ]
​​
0: "The code field is required."
​​
length: 1
​​
<prototype>: Array []
​
name: Array [ "The name field is required." ]
​​
0: "The name field is required."
​​
length: 1
​​
<prototype>: Array []
​
phone_home: Array [ "The phone home field is required." ]
​​
0: "The phone home field is required."
​​
length: 1
​​
<prototype>: Array []
​
phone_mobile: Array [ "The phone mobile field is required." ]
​​
0: "The phone mobile field is required."
​​
length: 1
​​
<prototype>: Array []
​
phone_work: Array [ "The phone work field is required." ]
​​
0: "The phone work field is required."
​​
length: 1
​​
<prototype>: Array []
​
<prototype>: Object { … }

Here's the request data(dd) I get for the backend end from the frontend.

 array:7 [
  "name" => null
  "code" => null
  "agent_id" => null
  "phone_home" => null
  "phone_work" => null
  "phone_mobile" => null
  "address_list" => array:1 [
    0 => array:1 [
      "address" => null
    ]
  ]
]

Response when address_list is added instead of address inside the validator

{"status":422,"errors":{"name":["The name field is required."],"code":["The code field is required."],"agent_id":["The agent id field is required."],"phone_home":["The phone home field is required."],"phone_work":["The phone work field is required."],"phone_mobile":["The phone mobile field is required."]}}
 
4
  • Can you console log what is the value of res.data.errors? Commented Dec 9, 2021 at 6:21
  • I have edited the question and added the console log for res.data.errors Commented Dec 9, 2021 at 6:27
  • Can you show me the request sent to the backend. I think it might be because you are passing address_list from frontend and have adress=>'required' at backend Commented Dec 9, 2021 at 6:35
  • @Danish I have added it to the question. Commented Dec 9, 2021 at 6:50

1 Answer 1

1

You may use 'address_list' => 'required' rather than

'address_list' => 'required'

So your final validator will be like this

 $validator = Validator::make($request->all(), [
            'name' => 'required',
            'code' => 'required',
            'agent_id' => 'required',
            'phone_home' => 'required',
            'phone_work' => 'required',
            'phone_mobile' => 'required',
            'address_list' => 'required',
        ]);

Or if you want to check if array_list is containing at least one address you can do that.

'address_list' => 'required|array|min:1' and also in case of you want to check that address_list must be in between lets say 1 to 10 you can do that as well

'address_list' => 'required|array|between:1,10'

attaching a link for anyone who want to study about it.

Sign up to request clarification or add additional context in comments.

9 Comments

now i am not getting an error shown at all. after trying your method.
@Mizy Because now there is no error if you want to check if address list contains atleast one address then you can do this as well 'address_list' => 'required|array|min:1' see updated answer to get better understanding
Ya i have updated the answer and checked my console log from the front end and the errors are not passed to the front end. I quite new to dynamic forms actually.
@Mizy have you seen my updated answer above? This will solve your issue if not you can paste the console.log again. WHy should error be passed if there are no errors? And also please mark the answer as accepted if this has helped you.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.