Learn the top 20 best practices for validating forms in React applications. From client-side validation to error handling, this blog post covers it all to help you build more user-friendly and efficient forms. Whether you're new to React or an experienced developer, these tips will help you create better forms and improve your React skills.
https://www.frontendmag.com/tips/react-form-validation-best-practices/
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
React Form Best Practices: A Comprehensive Guide
1. Home Tips Top 20 React Form Validation Best Practices
Top 20 React Form Validation Best
Practices
AUTHOR
admin
DATE
December 18, 2022
CATEGORY
Tips
Share
Form validation is an important aspect of web applications, as it helps to ensure that the data being
submitted is accurate, complete, and secure. In this post, I’ll be providing you with the top 20 React form
validation best practices.
I hope you find this post beneficial, whether you are new to React or an experienced front-end developer
trying to enhance your abilities. Alright, let’s get started!
Table of Contents
1. 1. Use controlled components for your forms
2. 2. Use a single source of truth for your form data
3. 3. Validate input on both the client side and server side
4. 4. Use a library for schema validation
5. 5. Don’t rely on HTML5 form validation
6. 6. Use descriptive, helpful error messages
7. 7. Use proper form field labels
8. 8. Use visual indicators for required fields
9. 9. Use the appropriate input type for each field
10. 10. Avoid using auto-complete for sensitive fields
11. 11. Avoid using complex regex patterns for validation
12. 12. Consider providing real-time feedback for field validation
13. 13. Use proper sanitizing for user-generated contents
14. 14. Use debounce function for remote validation
15. 15. Use aria attributes to improve accessibility
16. 16. Validate on blur
17. 17. Disable the submit button until the form is valid
18. 18. Avoid resetting the form on submission
19. 19. Improve form usability
Recent posts
React Query vs Axios: An
Absolute Beginner’s
Guide to choosing the
Right Library
December 15, 2022
Is TypeScript Faster Than
JavaScript? A
Comprehensive
Comparison
December 13, 2022
How To Master React JS:
The Ultimate Guide (10+
topics)
December 10, 2022
How to Learn React JS
Quickly: Complete
Beginner Guide with 7
Useful Steps
December 8, 2022
HOME TUTORIALS TIPS INSIGHTS CAREER
2. 1. Use controlled components for your forms
When you use controlled components, the value of each form element is managed by React state rather
than the DOM. React documentation suggests using controlled components to create forms.
You can easily manipulate form values and ensure that they are always up-to-date and consistent with
the application’s state. Plus, controlled components make it a breeze to validate user input and provide
helpful error messages because you’ll always have access to the current value of each form element.
So, using controlled components is essential for building reliable and user-friendly forms.
2. Use a single source of truth for your form data
You should keep all of your form’s data in one place. It avoids managing numerous copies of the same
data across different components. As a result, updating and manipulating your form data is also simpler.
Spreading your form data across multiple components can make it more difficult to keep track of what
data is stored where. It can cause confusion and mistakes, particularly in larger and more complex forms.
By using a single source of truth for your form data, your code is easier to understand and maintain.
3. Validate input on both the client side and server side
Client-side validation improves the user experience by providing immediate feedback when a user is
filling out your form. If a user tries to submit an email address that is not in the correct format, client-side
validation can display an error message right away, rather than waiting for the form to be submitted to
the server. This can help to prevent users from making mistakes and can make your forms more user-
friendly overall.
Server-side validation is also essential for protecting against malicious users who may try to bypass the
client-side checks. While client-side validation can catch many common mistakes and errors, it is not
foolproof and can be bypassed by determined attackers. Server-side validation is necessary to ensure
that the data received from the client is accurate and secure. This is especially important for sensitive
information, such as passwords and financial data.
By validating input on both the client side and the server side, you can provide a better user experience
while also protecting your application and users.
4. Use a library for schema validation
Many popular libraries are specifically designed to help with form validation tasks. These libraries
provide a convenient interface for defining and validating the structure of your form data.
20. 20. Test your form validation thoroughly
21. React form validation best practices conclusion
1. // Use Controlled Components
2. function ControlledInput() {
3. const [value, setValue] = useState('');
4.
5. function handleChange(event) {
6. setValue(event.target.value);
7. }
8.
9. return (
10. <input type="text" value={value} onChange={handleChange} />
11. );
12. }
13.
14. // Don't Use Uncontrolled Components
15. function UncontrolledInput() {
16. const inputRef = useRef();
17.
18. function handleSubmit(event) {
19. event.preventDefault();
20. console.log(inputRef.current.value);
21. }
22.
23. return (
24. <form onSubmit={handleSubmit}>
25. <input type="text" ref={inputRef} />
26. <button type="submit">Submit</button>
27. </form>
28. );
29. }
3. For example, you can use Yup, Zoi, or Zod to specify the types and formats of the data that the form
expects to receive. You can then use this schema to validate user input, providing helpful error messages
if there are any problems. This can save you time and effort rather than writing custom validation code.
Here is an example of using Yup for form validation:
5. Don’t rely on HTML5 form validation
HTML5 field validation is not always reliable, and may not work consistently across all browsers and
devices. Therefore, you should create custom validation to ensure the accuracy and security of your
forms.
There are several ways to implement custom client-side validation in React. As mentioned, you could use
a library to handle schema validation. Alternatively, you can use popular regular expression patterns or
write custom validation functions.
6. Use descriptive, helpful error messages
1. import React, { useCallback, useMemo } from "react";
2. import { useForm } from "react-hook-form";
3. import * as Yup from "yup";
4.
5. const useYupValidationResolver = (validationSchema) =>
6. useCallback(
7. async (data) => {
8. try {
9. const values = await validationSchema.validate(data, {
10. abortEarly: false,
11. });
12.
13. return {
14. values,
15. errors: {},
16. };
17. } catch (errors) {
18. return {
19. values: {},
20. errors: errors.inner.reduce(
21. (allErrors, currentError) => ({
22. ...allErrors,
23. [currentError.path]: {
24. type: currentError.type ?? "validation",
25. message: currentError.message,
26. },
27. }),
28. {}
29. ),
30. };
31. }
32. },
33. [validationSchema]
34. );
35.
36. const validationSchema = Yup.object().shape({
37. email: Yup.string()
38. .email("Invalid email address")
39. .required("Email is required"),
40. password: Yup.string()
41. .min(8, "Password must be at least 8 characters")
42. .required("Password is required"),
43. });
44.
45. export default function FormWithYup() {
46. const resolver = useYupValidationResolver(validationSchema);
47. const { handleSubmit, register } = useForm({ resolver });
48.
49. return (
50. <form onSubmit={handleSubmit((data) => console.log(data))}>
51. <input
52. id="email"
53. type="email"
54. {...register("email")}
55. />
56. <input
57. id="password"
58. type="password"
59. {...register("password")}
60. />
61. <input type="submit" />
62. </form>
63. );
64. }
4. When a user makes a mistake or provides invalid input, let them know what went wrong and how to fix
it. Vague or unhelpful error messages can be frustrating for users and discourage them from completing
your form. On the other hand, specific and helpful error messages can guide the user toward fixing
problems with their input.
There are a few key things to bear in mind when designing error messages for your forms in React.
First, ensure that your error messages are clear and easy to understand. Avoid using technical jargon or
convoluted language; instead, use straightforward language. Try to be as specific as possible when
describing the issue. For example, rather than simply saying “Invalid input,” it’s better to say “The email
address you entered is not in the correct format. Please enter a valid email address.”
Second, consider providing suggestions or examples to help the user correct their input. If you are asking
the user to enter a password, you could provide a list of best practices, such as “Your password should be
at least 8 characters long and contain a combination of letters, numbers, and special characters.”
7. Use proper form field labels
Provide appropriate form field labels to assist users in understanding what information is being asked.
Simple and clear labels are critical for improving form usability and readability. For example, “Email
address” is more clear and more concise than “Enter your email address.”
A good label should clarify the function of the form field and give the user context.
8. Use visual indicators for required fields
A visual indicator is a little visual hint that indicates which form elements are required. This can improve
the user experience by making it apparent which fields must be completed, as well as reducing the risk of
errors and omissions.
There are many different ways to implement a visual indicator for required fields in React. For instance,
you could use an asterisk (*) or another symbol next to the label for each required form element. You could
also use a different color or style for the labels or borders to make them stand out. Whatever method you
choose, the goal is to provide a clear and noticeable visual cue.
By making it clear which fields are required, you can help the user complete your form accurately and
efficiently.
9. Use the appropriate input type for each field
There are several different input types in HTML available, including text, passwords, emails, numbers,
and more. It’s critical to choose the input type that best fits the kind of data that the user is supposed to
enter.
You should use the email input type for email addresses, the password input for passwords, and the
number input type for numerical values.
By selecting the appropriate input type, you can assist the user in entering the relevant data while also
ensuring that data is correctly formatted and validated.
10. Avoid using auto-complete for sensitive fields
Auto-complete is a feature that automatically fills in form fields with data that has been previously
entered by the user. While auto-complete can be handy, it can also pose security problems and conflict
with custom validation.
Using auto-complete for critical inputs can risk your application’s security. When sensitive fields, such as
passwords or credit cards, are autocompleted, this information is exposed to other users who may have
access to the device.
In addition, auto-complete can interfere with custom validation by pre-filling form fields with data that
does not meet the required criteria. This can cause errors and confusion for the user, and can also lead to
inaccurate or invalid data being submitted to the server.
11. Avoid using complex regex patterns for validation
Complex regex patterns can be difficult to read and understand, even for experienced developers. They
can make your code harder to maintain and increase the risk of errors and bugs.
5. In addition, complex regex patterns can cause performance issues if not used carefully. They can be
resource-intensive to parse and can slow down your application.
To avoid these problems, it’s a good idea to:
use straightforward patterns that are easy to read and understand;
keep your regex patterns as concise as possible; and
avoid using multiple nested groups or other complex structures if not necessary.
By following these guidelines, you can use regexes effectively for form validation in React without running
into performance issues or other problems.
12. Consider providing real-time feedback for field validation
Real-time feedback can help to improve the user experience by providing guidance and assistance as the
user completes the form.
You could use form libraries, such as React Hook Form, React Final Form, or Formik, to handle validation
for you. These libraries provide real-time feedback and highlight errors with the user’s input.
Providing immediate feedback to the user can help them to fix any problems with their input more quickly.
13. Use proper sanitizing for user-generated contents
Sanitizing is the combination of escaping, filtering, and validating user input before sending data to the
server. Using proper sanitizing can help to secure your application from malicious input and prevent
security issues such as cross-site scripting attacks.
You should use a JavaScript XSS Sanitizer library, such as DOMPurify or sanitize-html, to handle sanitizing
for you. These libraries provide a convenient and easy-to-use interface for cleaning malicious form data
and protecting your application.
14. Use debounce function for remote validation
Remote validation refers to the process of validating form input by making a request to a server or other
external resources. This is often necessary when you need to check a user’s input against a database or
other data sources that are not available on the client side.
Requesting information from a server, on the other hand, can be time-consuming and resource-intensive,
especially if the user is typing quickly or making frequent changes to the form. It results in poor
performance and a negative user experience.
To avoid these issues, you can use the function. It works by delaying the remote validation
execution until a certain amount of time has passed without any new input. This helps improve the
performance of your forms.
15. Use aria attributes to improve accessibility
Using attributes to improve accessibility can help users of assistive technologies, such as screen
readers, to understand the purpose and current state of each form element. They make your forms more
accessible and friendly for users with disabilities.
There are many attributes to improve the accessibility of your forms in React. For instance, you
can use the attribute to provide a descriptive label for a form element. You can also use
the attribute to indicate that a form element is required, and the
attribute to specify that a form element contains invalid input.
16. Validate on blur
By validating on blur, you can help users catch errors early on and avoid having to submit the form
multiple times to fix errors. It’s a good idea to validate on blur in addition to validation on submit, as this
can help ensure that the form is completed correctly and efficiently.
17. Disable the submit button until the form is valid
debounce
aria
aria
aria-label
aria-required aria-invalid
6. You can prevent the user from submitting an invalid form by suppressing the submit button until the form
is valid. It reduces user irritation and misunderstanding while also preventing server failures. Before the
form can be submitted, the user will be prompted to correct the problem first.
Disabling the form’s submit button until the input is legitimate can also prevent multiple submissions. If a
user unintentionally clicks the submit button more than once, the form will only be submitted once
because the submit button is deactivated after the initial submission.
18. Avoid resetting the form on submission
If the form is reset after the user submits it, they may not understand their input has been cleared and
may attempt to resubmit the form. This can lead to errors as well as frustration for the user.
Furthermore, because it clears all of the data that has been entered, resetting the form can cause
problems with retaining the form’s state. This can make tracking the form’s progress more difficult and
can conflict with custom validation and other features.
19. Improve form usability
It is not enough to guarantee that the validation works properly; it is also necessary to examine how the
form appears and feels to the user.
Form usability includes the design of the form, its length, and the overall user experience. A difficult-to-
use or understand form can be frustrating for users, resulting in abandoned form submissions.
By considering usability, you may design a form that is simple and pleasurable for users to use. This is
especially true for forms that are essential to the operation of a website or application.
20. Test your form validation thoroughly
There are two main ways to test form validation: manually testing the form, and writing tests.
To test the form manually, you can try submitting the form with valid and invalid inputs and verify that
the validation is working correctly. This can be a helpful way to catch any issues with the validation and
ensure that it is working as intended.
In addition, writing tests to automatically check the form validation and ensure that it is not broken by
future code changes.
React form validation best practices conclusion
Thank you for joining me in this post! There’re many best practices in form validation, but I believe these
are the most important ones.
I hope that you have learned something new and useful and you now have a better understanding of how
to implement effective form validation in your React applications. By following the best practices outlined
in this post, you can ensure that your forms are accurate, secure, and easy to use.
I encourage you to continue learning and improving your skills as a React developer. If you have any
questions or concerns, please don’t hesitate to comment. Until next time, happy coding!
PREVIOUS ARTICLE
React Query vs Axios: An Absolute Beginner’s Guide
to choosing the Right Library