I'm trying to validate a form in React. Every time input is changed in the field, I try to validate it:
// Consutructor
this.state{
Form_errors:
Key1: false,
Key2: false
}
handleChange(e, name){
this.setState({
[name]: e.target.valueAsNumber
});
// validate fields
this.validate_field(e, name);
}
Then on form submit, I check every field is true:
handle_submit(e){
e.preventDefault();
// validate form immediately
this.validate_form();
}
validate_form(){
// check all fields are true
for (var field in this.state.form_errors) {
if(!this.state.form_errors[field]){
this.setState({
validated: false
});
return false;
}
}
this.setState({
validated: true
});
}
At this stage, validate_form()
only sees the recent field that was updated in handleChange
, so returns true after 1 iteration. If I console.log
the current state, only the current key value exists and not the others.
I also have conditional class in render()
that also sees only a single field at a time.
Why are the rest of the fields missing in state
?