React Js form validation Example
Thanks for your feedback!
Your contributions will help us to improve service.
How can I perform form validation in React.js?
The provided code demonstrates an example of form validation in a React.js application. The form contains several input fields such as first name, last name, username, email, password, confirm password, and an image upload field. The validation is performed when the form is submitted by calling the handleSubmit
function.
The useState
hook is used to manage the form data and the validation errors. The formData
state object holds the values of the form inputs, while the errors
state object stores the validation error messages for each input field.
The validateForm
function is responsible for validating the form inputs. It checks if the required fields are filled, validates the email format, ensures the password and confirm password match, and checks the size of the uploaded image. If any validation fails, the corresponding error message is set in the errors
state object.
The handleChange
function updates the formData
state object as the user types or selects a file, and it also clears the corresponding error message from the errors
state object.
The input fields are rendered within the form
element, and their values and error messages are bound to the state objects. The CSS classes form-input
and form-input-error
are conditionally applied to style the input fields based on the presence of errors.
When the form is submitted and passes validation, the form data is logged to the console.