Reactive Form Validation
This post will discuss how form validation was implemented within the NextJs application.
In order to achieve this a custom hook was created named useForm. Three interfaces were created and are required to use the hook. Each form requires a validation schema, an initial state made consisting of subfields.
This hook can be used for any standard inputs such as text inputs and text areas.
useForm Hook In Full
The following extract shows the hook in full. Form input values entered by the user are checked against a regular expression when new characters are typed. If the text does pass the RegExp.test( ) method then the error contained within the validation schema for the given input is used in the form state. This change in state updates the user interface to display the error to the user notifying them of a problem.
Example Usage
Once the validation schema has been configured the form can be created.
The results of the real time form validation can be seen in the following screenshot. The title field is a required field, however is missing a value and so will provide an error telling the user that it is a required field. The excerpt field has an illegal character and so will notify the user of this. Finally, the content input contains no errors and so does not provide an error or highlight the input as red.
This post has covered how the NextJs application provides form validation to users in real time by using a custom created React Hook that uses callback functions, internal state and regular expressions. The same hook was used for the login page and the search page.





Comments
Post a Comment