Home > Mobile >  React js Laravel dynamic form fields validation
React js Laravel dynamic form fields validation

Time:12-10

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."]}}
 

CodePudding user response:

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.

  • Related