Tracking validation errors with state

We are going to track the validation error messages in the 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. We are going to store the validation errors in the Form component state as follows:

  1. Let's start by creating interface for the errors in Form.tsx after the Values interface:
export interface Errors {
[key: string]: string[];
}

This is an indexable type where an array of validation error messages is associated with a field name.

  1. We are only going to render a validation error if the field has been touched and lost focus, so we need to track whether this is the case for each field. Let's create an interface for this:
export interface Touched {
[key: string]: boolean;
}

  1. Next, we'll add the validation errors and whether a field has been touched to the form context along with functions to set them:
interface FormContextProps {
values: Values;
setValue?: (fieldName: string, value: any) => void;
errors: Errors;
validate?: (fieldName: string) => void;
touched: Touched;
setTouched?: (fieldName: string) => void;
}

export const FormContext = createContext<IFormContext>({
values: {},
errors: {},
touched: {}
});
  1. Let's add the field validation errors and whether fields have been touched to the Form component state:
const [values, setValues] = useState<Values>({});
const [errors, setErrors] = useState<Errors>({});
const [touched, setTouched] = useState<Touched>({});
  1. We can add the field validation errors and whether fields have been touched to the context provider:
<FormContext.Provider
value={{
values,
setValue: (fieldName: string, value: any) => {
setValues({ ...values, [fieldName]: value });
},
errors,
validate,
touched,
setTouched: (fieldName: string) => {
setTouched({ ...touched, [fieldName]: true });
}
}}
>

Notice that we use a spread expression to update the new touched state.

These additions to the context will allow the Field component to access the validation errors and whether it has been touched. We'll need access to these later when we render the validation errors. 

  1. For now, we'll add a skeleton validate function just below the state declarations:
const [touched, setTouched] = useState<Touched>({});

const validate = (fieldName: string): string[] => {
return [];
};

We'll finish implementing this later.

The validation errors are now in the Form component state and in the form context for the Field component to access. 

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

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