How to implement effective form validation for a User Management system with fields like username, age, and birthdate. This guide explains how to validate input formats, enforce rules (e.g., age limits, valid usernames), and handle errors gracefully to ensure accurate and user-friendly data collection.
I previously developed a small UserManagement application.
I will try to develop this application to reach the state shown in the image below. (User Management Validation)
Let's look at the form structure on the right side of this application today. In the structures I defined:
The Create Button is not inside the Form Element. It stands in a separate place in the DOM Tree structure.
We expect:
Since the Create button and Form structure are distant from each other in this part, I actually find Formik and Yup validation more suitable.
Form Submit Validation is the validation process performed on all form data. This part performs the flow shown in the image below.
After these validation operations, warnings on relevant UI components or more general Toast Messages are shown to the user.
There is also a need for validation structures that will provide immediate feedback to the user when the field is empty or when the field does not comply with certain limits.
These structures need to trigger the onChange and onBlur events of Form Elements and run the relevant validation again.
First, running its own validation structure, catching these change events, calling validation in these operations, storing errors in state, and displaying warnings in relevant parts of screen components.
While we can integrate the validate method we used in our own method with the Formik structure, we can create a Schema with the Yup structure similar to React PropTypes.
const SignInSchema = Yup.object().shape({
email: Yup.string().email().required("Email is required"),
password: Yup.string()
.required("Password is required")
.min(4, "Password is too short - should be 4 chars minimum"),
});
Then we can pass this Schema to the Formik structure:
<Formik
initialValues={initialValues}
validationSchema={signInSchema}
onSubmit={(values) => {
console.log(values);
}}
Although I like the Formik + YUP structure, error integration needs to be done manually in components.
Either we will add the styling structure in components through className natively, or there are stylings provided by UI Component libraries like Antd's Form structures, which can be integrated with Formik + YUP structure.
In my example, I used the Antd UI Library. Here you can add rules to AntD