How to Catch and Parse Errors Properly in React form Submission Handler ?
Last Updated :
26 Jul, 2024
We use forms a lot to get information from users, like their email, username, and password. Users send us this info through the forms, and we store it on the web server. The Form is an element that is used on a large scale in many websites which makes it an integral component. Creating a Form in ReactJS is similar to HTML but in HTML the form we create is static, but in React we could add many unique functionalities like validations, etc.
What is Formsy?
Formsy is an open-source library that is a form input-builder and validator for React. We can catch and parse errors using this library. It helps us to deal with these two crucial things:
- Validation and error messages
- Handling form submission
Steps to Create the React Application
Step 1: Creating React ApplicationĀ
npx create-react-app appname
Step 2: After creating your project folder, Go into your project folder.
cd appname
Step 3: Now we can add Formsy for building forms and handling errors.
npm i formsy-react
Project Structure:
Project StructureThe updated dependencies in package.json file will look like:
"dependencies": {
"formsy-react": "^2.3.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}
Step 4: Create a file InputField.js which contains an HTML input tag. So that we can import it and use it in our forms(in App.js).
Example: First import withFormsy from formsy-react by writing the below code in InputField.js.
import { withFormsy } from 'formsy-react'
After importing withFormsy from formsy-react, we created an input field and added some common HTML attributes. We need to import Formsy from formsy-react.
import Formsy from 'formsy-react'
JavaScript
import React, { useState } from 'react'
import './App.css'
import Formsy from 'formsy-react'
import InputField from './InputField'//Line 4
// Line 6
const errors = {
isEmail: 'You have to type a valid email',
maxLength: 'You cannot type more than 25 characters',
minLength: 'You must type more than 6 characters',
}
function App() {
const [canSubmit, setCanSubmit] = useState(false); //Line 14
const disableButton = () => {
setCanSubmit(false);
}
const enableButton = () => {
setCanSubmit(true);
}
const submit = () => {
console.log('Form is Submitted');
}
return (
<div className='app'>
<h1>Form in React Js</h1>
<Formsy className='form'
onValidSubmit={submit}
onValid={enableButton}
onInvalid={disableButton}>
<InputField label="First Name"
type="text" name="email"
validations="maxLength:25"
validationErrors={errors}
placeholder="Type your First Name"
required />
<InputField label="Last Name"
type="text" name="lastname"
validations="maxLength:25"
validationErrors={errors}
placeholder="Type your last Name"
required />
<InputField label="Email address"
type="text" name="email"
validations="maxLength:30,isEmail"
validationErrors={errors}
placeholder="Type your email address..."
required />
<InputField label="Password"
type="password" name="password"
validations="minLength:6"
validationErrors={errors}
placeholder="Type your password..."
required />
<button type="submit"
disabled={!canSubmit}>
Submit
</button>
</Formsy>
</div>
)
}
export default App
JavaScript
import { withFormsy } from 'formsy-react'
import React from 'react'
class MyInput extends React.Component {
constructor(props) {
super(props)
this.changeValue = this.changeValue.bind(this)
}
changeValue(event) {
this.props.setValue(event.currentTarget.value);
}
render() {
const errorMessage = this.props.errorMessage;//Line 15
return (
<div className='input-row'>
<label>
{this.props.label}
{this.props.isRequired ? '*' : null}
</label>
<input onChange={this.changeValue}
type={this.props.type}
placeholder={this.props.placeholder}
value={this.props.value || ''} />
<span>{errorMessage}</span>//Line 21
</div>
)
}
}
export default withFormsy(MyInput) //Line 27
We will wrap all input fields with the Formsy component which gives us some properties which help us with form validation. The properties that are helpful for us i.e. validations and validationError.
- validations: Here we can pass some validators separated by a comma. And with the validator, we can pass some arguments by using ":".
- validationerrors: You can manually pass down errors to your form. It will show up when the requirement is not met.
In this way, we can add our own conditions, and error messages as per your requirements.
Wrapping with a Formsy tag also gives us functionalities like OnValidSubmit, OnValid, and OnInvalid which helps us in Form Submission.
- onValidSubmit: It ensures that what will be done after we submit the form with no errors, In this case, submit method will run and submits our form.
- onValid: It ensures the form can be only submitted when all input fields are valid. So in this case, if all the input fields are valid then we call the enableButton method which enables the submit button with the help of the state variable canSubmit defined above in Line 14.
- onInvalid: It ensures the form cannot be submitted when one of the input fields is invalid. So in this case, if one of the input fields is invalid then we call the disableButton method which disables the submit button with the help of a state variable canSubmit defined above in Line 14.Ā
Step 5: Run the application using the following command from the root directory of the project:
npm start
Output: Open your browser and go to http://localhost:3000
Similar Reads
How to create a global Promise Rejection Handler in JavaScript ?
In this article, we will try to understand firstly how we create a Rejected Promise, and later we will see how we may create a Global Promise Rejection Handler which will try to handle (somehow) that Rejected Promise created earlier in JavaScript. Let us first try to understand how we create a Promi
2 min read
How to Handle Errors for Async Code in Node.js ?
Handling errors effectively in asynchronous code is crucial for building robust and reliable Node.js applications. As Node.js operates asynchronously by default, understanding how to manage errors in such an environment can save you from unexpected crashes and ensure a smooth user experience. This a
4 min read
How to handle server-side errors in Redux applications ?
It is essential to deal with server-side errors while building reliable Redux applications. This ensures a seamless user experience, even if problems occur during server requests. This guide will explain the effective management of server errors in the Redux architecture through Redux Thunk middlewa
3 min read
How to Handle Errors in React Redux applications?
To handle errors in Redux applications, use try-catch blocks in your asynchronous action creators to catch errors from API calls or other async operations. Dispatch actions to update the Redux state with error information, which can then be displayed to the user in the UI using components like error
4 min read
JavaScript - How to Handle Errors in Promise.all?
To handle errors in Promise.all(), you need to understand that it fails immediately if any of the promises reject, discarding all resolved values. This behavior can lead to incomplete operations and potential application crashes. The best way to manage errors in Promise.all() is by using .catch() in
3 min read
How to handle asynchronous operations in custom hooks?
Custom Hooks in React are reusable JavaScript functions that enable the encapsulation of stateful logic, promoting cleaner and more modular code in components. When dealing with asynchronous operations in custom hooks, you want to ensure your hook can handle tasks that don't finish immediately, like
3 min read
Explain the process of submitting forms and handling form submissions in Redux
Redux is a state management library for React applications. It helps you manage the state of your application in a centralized way. It provides a way to store and manage the state of your application in a single object called the store. In this article, we will learn about How to handle form submiss
5 min read
How To Handle Errors in React?
Handling errors in React is essential for creating a smooth user experience and ensuring the stability of your application. Whether you're working with functional or class components, React provides different mechanisms to handle errors effectively. 1. Using Error BoundariesError boundaries are a fe
5 min read
Global error handler not catching unhandled promise rejection ?
Global Error: The starting value problem for a system of ordinary differential equations and the global, or true, error produced by one-step procedures are both studied. On an asymptotic global error expansion, some techniques for approximating this global error are based. Unhandled promise rejectio
4 min read
How to Catch an Error from External Library and Store it in a String in JavaScript ?
When using an external library in our code, we may encounter errors. It is essential to catch these errors and handle them gracefully. In some cases, we may want to store the error message in a string for further processing or display it to the user. In this article, we will learn how to catch an er
3 min read