Forms are an integral part of how users interact with our websites and web applications. Validating the data the user passes through the form is a critical aspect of our jobs as web developers. However, it doesn’t have to be a pain-staking process. In this article, we’ll learn how Formik handles the state of the form data, validates the data, and handles form submission.
As developers, it is our job to ensure that when users interact with the forms we set up, the data they send across is in the form we expect.
In this article, we will learn how to handle form validation and track the state of forms without the aid of a form library. Next, we will see how the Formik library works. We’ll learn how it can be used incrementally with HTML input fields and custom validation rules. Then we will set up form validation using Yup and Formik’s custom components and understand how Yup works well with Formik in handling Form validation. We will implement these form validation methods to validate a simple sign up form I have set up.
Note: This article requires a basic understanding of React.
On its own, React is powerful enough for us to be able to set up custom validation for our forms. Let’s see how to do that. We’ll start by creating our form component with initial state values. The following sandbox holds the code for our form:
Form validation without the use of a library
const Form = () => {
const intialValues = { email: "", password: "" };
const [formValues, setFormValues] = useState(intialValues);
const [formErrors, setFormErrors] = useState({});
const [isSubmitting, setIsSubmitting] = useState(false);
}
With the useState
hook, we set state variables for the formValues
, formErrors
and isSubmitting
.
formValues
variable holds the data the user puts into the input fields.formErrors
variable holds the errors for each input field.isSubmitting
variable is a boolean that tracks if the form is being submitted or not. This will be true
only when there are no errors in the form.const submitForm = () => {
console.log(formValues);
};
const handleChange = (e) => {
const { name, value } = e.target;
setFormValues({ ...formValues, [name]: value });
};
const handleSubmit = (e) => {
e.preventDefault();
setFormErrors(validate(formValues));
setIsSubmitting(true);
};
const validate = (values) => {
let errors = {};
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/i;
if (!values.email) {
errors.email = "Cannot be blank";
} else if (!regex.test(values.email)) {
errors.email = "Invalid email format";
}
if (!values.password) {
errors.password = "Cannot be blank";
} else if (values.password.length < 4) {
errors.password = "Password must be more than 4 characters";
}
return errors;
};
useEffect(() => {
if (Object.keys(formErrors).length === 0 && isSubmitting) {
submitForm();
}
}, [formErrors]);
Here, we have 4 form handlers and a useEffect
set up to handle the functionality of our form.
handleChange
formValues
state and updates the state as the user types.validate
formValues
object as a argument to this function, then based on the email
and password
meeting the validation tests, the errors
object is populated and returned.handleSubmit
formErrors
state variable is populated with whatever errors may exist using the setFormErrors(validate(formValues))
method.useEffect
formErrors
object is empty, and if isSubmitting
is true
. If this check holds true, then the submitForm()
helper is called. It has single dependency, which is the formErrors
object. This means it only runs when the formErrors
object changes.submitForm
: this handles the submission of the form data.return (
<div className="container">
<h1>Sign in to continue</h1>
{Object.keys(formErrors).length === 0 && isSubmitting && (
Signed in successfully
)}
<form onSubmit={handleSubmit} noValidate>
<div className="form-row">
<label htmlFor="email">Email</label>
<input
type="email"
name="email"
id="email"
value={formValues.email}
onChange={handleChange}
className={formErrors.email && "input-error"}
/>
{formErrors.email && (
{formErrors.email}
)}
</div>
<div className="form-row">
<label htmlFor="password">Password</label>
<input
type="password"
name="password"
id="password"
value={formValues.password}
onChange={handleChange}
className={formErrors.password && "input-error"}
/>
{formErrors.password && (
{formErrors.password}
)}
</div>
<button type="submit">Sign In</button>
</form>
</div>
);
Here, we pass in the handleChange
helper functions to the inputs’ onChange
attribute. We link the value of the inputs to the formValues
object, making them controlled inputs. From the React docs, controlled inputs are inputs whose values are controlled by React. An input-error style is applied if there are any errors related to that specific input field. An error message is conditionally displayed beneath each input if there are any errors related to that specific input field. Finally, we check if there are any errors in the errors object and if isSubmitting
is true. If these conditions hold true, then we display a message notifying the user that they signed in successfully.
With this, we have a fully functional and validated form set up without the aid of a library. However, a form library like Formik with the aid of Yup can simplify the complexities of handling forms for us.
#react #javascript #programming #developer #web-development