Tracking validation error messages

We need to track the validation error messages in state as the user completes the form and fields become valid or invalid. Later on, we'll be able to render the error messages to the screen.

The Form component is responsible for managing all the form states, so we'll add the error message state to there, as follows:

  1. Let's add the validation error message state to the form state interface:
interface IErrors {
[key: string]: string[];
}

interface IState {
values: IValues;
errors: IErrors;
}

The errors state is an indexable key/value type where the key is the field name and the value is an array of validation error messages.

  1. Let's initialize the errors state in the constructor:
constructor(props: IFormProps) {
super(props);
const errors: IErrors = {};
Object.keys(props.defaultValues).forEach(fieldName => {
errors[fieldName] = [];
});
this.state = {
errors,
values: props.defaultValues
};
}

The defaultValues prop contains all the field names in its keys. We iterate through the defaultValues keys, setting the appropriate errors key to an empty array. As a result, when the Form component initializes, none of the fields contain any validation error messages, which is exactly what we want.

  1. The Field component is eventually going to render the validation error messages, so we need to add these to the form context. Let's start by adding these to the form context interface:
interface IFormContext {
errors: IErrors;
values: IValues;
setValue?: (fieldName: string, value: any) => void;
}
  1. Let's add an errors empty literal as the default value when the context is created. This is to keep the TypeScript compiler happy:
const FormContext = React.createContext<IFormContext>({
errors: {},
values: {}
});
  1. We can now include the errors in the context value:
public render() {
const context: IFormContext = {
errors: this.state.errors,
setValue: this.setValue,
values: this.state.values
};
return (
...
);
}

Now, the validation errors are in the form state, and also in the form context for the Field component to access. In the next section, we'll create a method that is going to invoke the validation rules.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.4.181