I am new to React 16, Please find the below code which I am using for Validation using hooks. I have used a reusable Select box and on the value of the option, I am showing an input box. Validation rules: if the select box is empty on click of submit i want to show error and hide it when I select a value then if the input box is empty want to show error and hide when we give valid input. Problem : When error message appears for select box and after selecting the value when input box appears it shows the error for that too so it's like the first look of input box is with the validation error. I want to show it when user clicks submit button and onchange after valid entry it should go away.
Really appreciate the help!
const Step3 = (props) => {
const [values, setValues] = useState({});
const [errors, setErrors] = useState({});
const [isSubmitting, setIsSubmitting] = useState(false);
const [isSent, setIsSent] = useState(false);
const { handleChange, handleSubmit } = useForm(validate);
useEffect(() => { if (Object.keys(errors).length === 0 && isSubmitting) { } }, [errors]);
const onChange = (event) => {
event.persist && event.persist();
setIsSubmitting(false);
const newValues = {...values,[event.target.name]:event.target.value};
isSent && setErrors(validate(newValues));
setValues(values => newValues);
};
const handleSubmit = (event) => {
if (event) event.preventDefault();
setErrors(validate(values));
setIsSubmitting(true);
setIsSent(true);
};
return (
<div>
<form onSubmit={handleSubmit} noValidate>
<Select
name="abc"
label="ABC"
options={options}
onChange={onChange}
/>
{errors.abc && (<p className="help is-danger">{errors.abc}</p>)}
{values.abc=='Apple' && <input name="xyz" value={values.xyz||'' onChange={onChange}}/>
{errors.xyz && (<p className="help is-danger">{errors.xyz}</p> )}
}
<Button type={submit}>
Submit
</Button>
</form>
</div>
);
};
function validate(values) {
let errors = {}
if (!values.abc)
{ errors.abc= ' required'; }
if (!values.xyz) {
errors.xyz= 'required';
}
return errors;
};