Form validations in ReactJS
Completely relying on the backend for the entry of proper data into databases, is not the right practice. We should disallow the submission of data that does not fulfill the criteria for each entry. This reduces API calls to the backend server. This is called Client-side Validation.
Not only this but even after submission to the backend, some errors might arise which should also be displayed to the user for further correction or assistance. This is called Server-side Validation.
Possible Types of Validation
- Disallow empty submissions
- Regex matching for fields (like password, email etc.)
- Length of Data submitted
There can be other possible types of form validation too. I have just mentioned a few.
Implementation
Instead of a check on every field in a specific function, simpler methods to disallow empty data submission would be disabling the Submit button.
In your button component do the following:
<Button
disabled={ !this.state.name || !this.state.email }
/>
Add all the required fields similarly. Also, ensure adding the required
attribute to the field component also.
For specific fields like Password and Email, we need to ensure Regular Expressions (RegEx) for proper entry of data.
A sample regex for password will be:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$
The first part (?=.*[a-z])
ensures a small letter, similarly second part ensures a capital letter, next a digit, next a special character, next any alphanumeric character, and the last one limits the minimum length of data to be 8. If we want a maximum limit then modify the expression to {8,32}
, which means a minimum of 8 characters and a maximum of 32 characters allowed.
You can learn more about RegEx from here:
…and there can be other ways to do the same.