Saturday, September 21, 2024
Google search engine
HomeLanguagesHow to Catch and Parse Errors Properly in React form Submission Handler...

How to Catch and Parse Errors Properly in React form Submission Handler ?

We extensively use forms to take inputs from users so that users can interact with the web server. A form contains different kinds of information like email-id, username, and password which users send us and we can store it in 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. In building form validation, handling errors becomes tough and it is crucial that how can we give users a proper response and handle errors properly.

There are a lot of ways you can do it. Here we will use the Formsy library for form error handling and validation.

 

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:

  1. Validation and error messages
  2. Handling form submission

Here is the step-by-step guide for using Formsy in your projects:

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: It will look like the following.

 

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).

InputField.js: First import withFormsy from formsy-react by writing the below code in InputField.js.

import { withFormsy } from 'formsy-react'

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


After importing withFormsy from formsy-react, we created an input field and added some common HTML attributes. Line 15 indicates an error message will be passed only if the component is invalid. If one of the components (i.e. input field) is invalid then the error message will be shown to the user in line 21. If the components(i.e. input field) are valid i.e. passes our requirements then no error message will be shown to the user. 

Note: All Formsy input components must be wrapped in the withFormsy higher-order component, which provides the properties and methods through props. Line 27 indicates wrapping a component (MyInput) inside another component (withFormsy), the wrapped component receives all the props of the container, along with a new prop, data which it uses to render its output.

Step 5: First, we need to import Formsy from formsy-react. Write the below code to import it into your App.js file.

import Formsy from 'formsy-react'

App.js

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


In App.js, We will build our form logic. Starting with line 6, there are some error messages we have written so that we will show errors to users when one of the input field values doesn’t match our requirements. You can change it as per your requirements. Then we need the inputField component by importing it as written in Line 4. 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.

  1. validations: Here we can pass some validators (like maxLength, minLength, isNumeric, isEmail) separated by a comma. And with the validator, we can pass some arguments by using “:” (like maxLength:25 so if the length of the value of the input field is more than 25 it will throw the user an error).
  2. validationerrors: You can manually pass down errors to your form. It will show up when the requirement is not met (i.e. for example when the length of the value of the input field is more than 25 characters).

Other properties like placeholder, type, label, etc. all are common HTML attributes.

In this way, you can add your 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. 

There are a lot of functionalities that Formsy gives us that you can explore yourself.

Step 6: 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/, you will see the following output: 

In the below output, we are unable to register because the password length doesn’t match the requirements.

 

The register button works when the conditions of all input fields are valid.

 

In this way, you can handle form errors and parse them. Most importantly it will help you build complex forms easily for your projects where there are too many things to handle. This comes in handy which makes your project efficient and saves your time.  

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments