reactchel
reactchel

Reputation: 264

How to make field validation?

How to make field validation?

I have an object with fields from which I generate a form, and when submitting, I need to check each field so that it is not empty, I do this, but it doesn’t work

My form:

    const [volunteerData, setVolunteerData] = useState({
    fullName: {
      value: '',
      type: "text",
      placeholder: "Name",
      label: "Name"
    },
    phone: {
      value: '',
      type: "text",
      placeholder: "Phone number",
      label: "Phone number",
      mask: "+7(999) 999 99 99"
    }
    )}

Render form:

const onHandleRenderForm = () => {
    return Object.keys(volunteerData).map((items, idx) => {
        const control = volunteerData[items];
        return (
            <div key={idx} className="content-data-box">
                <label>{control.label}</label>
                <InputMask 
                    type={control.type} 
                    placeholder={control.placeholder}
                    mask={control.mask}
                    onChange={e => onHandleFormData(e, items)}
                />
            </div>
        )
    })
};

onChange input:

const onHandleFormData = (e, items) => {
    const before = {...volunteerData};
    const after = {...before[items]}

    after.value = e.target.value;
    
    before[items] = after;
    setVolunteerData(before);
};

onClick (submit button):

const onHandleErrorBoundary = () => {
    Object.keys(volunteerData).map(items => {
        const errorData = items.value === '';
        console.log(errorData)
    })
};

Upvotes: 1

Views: 59

Answers (1)

iamhuynq
iamhuynq

Reputation: 5539

Change items.value === '' to volunteerData[items].value !== ""

const onHandleErrorBoundary = () => {
    Object.keys(volunteerData).map(items => {
      const errorData = volunteerData[items].value !== "";
      return console.log(errorData);
    });
};

you can check here codesandbox

Upvotes: 1

Related Questions