In web development, form validation is very important as it ensures that the data entered by users is in the correct format, complete and properly sanitized to prevent any security issues. It also helps in maintaining the integrity of the data which is getting collected and also enhances the user experience.
In this article, we will discuss how to create a Next js form with examples and cover almost all the field types and required validation. Most important we will discuss how to implement it in the correct and proficient way.
To achieve this we will explore built-in methods and also the third-party library which can make m=work easy and fast. Let’s get started!
[lwptoc]
What is Form Validation?
Form validation is a process in which we check if the data entered by the user in the form is in the correct format and also its complete. Form validation works like a gatekeeper to ensure that only valid information is consumed by our application.
Data can be a threat or boon, so proper validation of information plays a crucial role in data integrity and prevent entry of incorrect data which can be dangerous as it can exploit the valuable data in databases.
It can improve the usability and security of the application but at the same time provides instant feedback about the data they are entering and allow them to correct it right away.
Let’s have a look at a simple example of form validation in Next.js using built in HTML validation:
import React from 'react';
class MyForm extends React.Component {
render() {
return (
<form>
<label>
Name:
<input type="text" name="name" required />
</label>
<label>
Email:
<input type="email" name="email" required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default MyForm;
In this example, the required
attribute ensures that the user cannot submit the form without filling out the name and email fields. If the user tries to submit the form without filling in these fields, the form will display an error message. We also used the pattern attribute to validate the email field using a regular expression to check if the email is in the correct format.
Limitations of HTML Native Validations
Using the HTML’s native validation is easy to implement but there are a few of the following limitations:
Limited Validation Rules
The built-in methods provide only basic validation like required fields and pattern matching. But they do not support complex validation rules like validating two fields are the same or not like password and confirm password.
No Custom Error Messages
Buil in methods show a standard message format to users which cannot be customized according to the theme.
No Server-Side Validation
Using the build methods we can only validate on the client side, but it’s always a good practice to validate the data at the server side as well to make applications more robust and secure.
In next section we discuss how to overcome these limitations by using the third part liberaries.
Using External Libraries for Form Validation
We discussed various limitations which can come up while using the build in validation techniques. These can easily be overcome by using external libraries like Formik, react-hook-form, and Yup.
Let’s take a look at how to install and use these libraries for form validation in Next.js.
Formik
Formik is a popular library for building forms in React and Next.js. To install Formik, execute the following command:
npm install formik
Here’s an example of a Next.js form with required validation using Formik:
import React from 'react';
import { Formik, Form, Field } from 'formik';
const MyForm = () => (
<Formik
initialValues={{ name: '', email: '' }}
validate={values => {
const errors = {};
if (!values.name) {
errors.name = 'Required';
}
if (!values.email) {
errors.email = 'Required';
} else if (
!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)
) {
errors.email = 'Invalid email address';
}
return errors;
}}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 400);
}}
>
{({ isSubmitting }) => (
<Form>
<Field type="text" name="name" />
<Field type="email" name="email" />
<button type="submit" disabled={isSubmitting}>
Submit
</button>
</Form>
)}
</Formik>
);
export default MyForm;
In the above example, we used Formik to implement form validation in a more comprehensive way. Formik allows to add of customer validation logic and controls the error message customisations.
Increasing User Engagement Using Forms
We can enhance user engagement by implementing features like auto-completion and conditional fields.
Auto-completion saves a lot of time and effort of user by suggesting the possible input terms.
Conditional fields can make forms more dynamic by showing and hiding the form field based on previous selections by users..
Example of a form with an auto-complete field in Next.js:
import React from 'react';
import Autocomplete from '@material-ui/lab/Autocomplete';
import TextField from '@material-ui/core/TextField';
const options = ['Option 1', 'Option 2', 'Option 3'];
export default function AutoCompleteField() {
return (
<Autocomplete
options={options}
renderInput={(params) => <TextField {...params} label="Auto-complete field" variant="outlined" />}
/>
);
}
We used Meteril UI to create an Autocomplete form field where users can start typing to see suggestions under the form field.
Conclusion
In this guide, we focused on how to add Form fields and add validation by using the build in methods which can have limitations to compete with complex validation requirements. Also, we discussed how to overcome these limitations by using external third part libraries.