How can I implement FormValidation in React?

react-form validation - npm
react form validation hooks
react form validation best practices
react input required attribute
react form validation - stack overflow
custom form validation in react js
react-bootstrap form validation
react form validation medium

I created a FormValidation Function for my React-App Project. I use the tutorial "Form Validation in React" to implement this. You can find a demonstration Project on Github. The Problem is, that this FormValidation doesn't work in my Project. I don't know why.

I am aware that it takes time to help me, but I would be very grateful for it because I have little knowledge about that. Because the files are too large to insert here, I created SandBox.io project. This is exactly the same project that I use myself:

Thanks for our help. For my React-App, I am using the Evergreen UI Framework. You can find the Props for the TextInputFields (Which I use) here.

You can write a separate module for form validation.

Validation module
import { emailRegex } from './regex'

export function validateEmail(email) {
  if (!email.length) {
    return {
      status: true,
      value: 'Email is required'
    }
  } else if (!emailRegex.test(email)) {
    return {
      status: true,
      value: 'Email is invalid'
    }
  }
  return {
    status: false,
    value: ''
  }
}

export function validatePhone(phone) {
  if (!phone.length) {
    return {
      status: true,
      value: 'Mobile number is required'
    }
  } else if (isNaN(phone) || phone.length !== 10) {
    return {
      status: true,
      value: 'Mobile number is invalid'
    }
  }

  return {
    status: false,
    value: ''
  }
}

This module will always return a object of signature { status, value }. Where status is whether you want to show the error or not and value is the respective error message.

For example: if my email is invalid it will return { status: true, value: 'Email is invalid' }

Now in my react component I can simply import these validators and use it.

Form component
import { validateEmail, validatePhone } from './../validators'

class Form extends React.Component {
  constructor() {
      this.state = {
        phoneErr: {
          status: false,
          value: ''
        },
        emailErr: {
          status: false,
          value: ''
        }
    }
  }
  handleSubmit() {
    if(this.checkFormStatus()) {
      // submit form
    }
  }
  checkFormStatus() {
      // form validation middleware
      const { email, phone } = this.state
      const emailErr = validateEmail(email)
      const phoneErr = validatePhone(phone)

      if (!emailErr.status && !phoneErr.status) {
        return true
      } else {
        this.setState({
          emailErr,
          phoneErr
        })
        return false
      }
    }

    render() {
      return (
        <div>
          <div className="form-group">
             <label>Member Phone Number</label>
             <input
                onChange={this.handleChange}
                value={this.state.phone}
                name="phone"
                type="text"
                maxLength={10}
              />
                { phoneErr.status && <p className="form-group__error">{ phoneErr.value }</p>}
        </div>

        <div className="form-group">
          <label>Email Address</label>
          <input
            onChange={this.handleChange}
            value={this.state.email}
            name="email"
            type="text"
          />
         { emailErr.status && <p className="form-group__error">{ emailErr.value }</p>}
      </div>

      <Button onClick={this.handleSubmit} primary>Add member</Button>

        </div>
      )
    }
}

I have separated the checkFormStatus function as a validation middleware. The idea here is to separate the validation part from my react component. This way I have decoupled my form validation logic. I just need two things status and message. Now I can use my form validation in my other applications too.

How to use HTML5 form validations with React, Add input, validation labels, and state in React Component. Using <form> element to enclose our input fields. We first need to make sure that our  React allows you to easily display errors as the form is being filled so the user doesn’t have to fill in the entire form, press the submit button, then try to figure out what they got wrong. This does not mean React can be used to make a form secure. Hackers can bypass your React form altogether, passing variables directly to the server.

I recommend using libraries. Form creation and validation tends to be rather painful. Using lib makes life easier in general:

ex.

https://react-form.js.org/#/

And comparison of different ones:

https://codebrahma.com/form-libraries-in-react/

Creating Your Own React Validation Library: The Basics (Part 1 , Understanding how a form validation library would work is paramount. Last year, I of how other libraries implement “the magic of validation”. The idea of the component is the following. In React, typically, we don’t want to reload the page on form submission. Instead, we want to send the data with ajax request. It doesn’t matter for our validation component how and what data is submitted.

If you project has upgraded to latest React with Hook, then you can try my package below:

Github: https://github.com/bluebill1049/react-hook-form

Website: http://react-hook-form.now.sh

example below:

import React from 'react'
import useForm from 'react-hook-form'

function App() {
  const { register, handleSubmit, errors } = useForm() // initialise the hook
  const onSubmit = (data) => { console.log(data) } // callback when validation pass

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="password" ref={register({ required: true })} /> 

      <input name="lastname" ref={register({ required: true })} /> 

      <input type="submit" />
    </form>
  )
}

How to do Simple Form Validation in #Reactjs, That opens http://localhost:3000/ where our new app is running. Next, let's add bootstrap so that we can style our form easily: $ npm install react-  Managing Form Validation with Fonk. On the other hand, handling form validation on your own can be tempting, but you have to cover scenarios like: You may want to validate a single field, or run all field validations. You may want to add record level validations. You may want to fire async validations.

Form Validation in React - Code Monkey, So I wrote my own react validation code, and am sharing it with you. project that uses this code to implement a basic signup form. Among  This tutorial aims and leverages your existing knowledge in HTML5 Constraint API Validation and React as much as possible so that you can get started doing it yourself right away. This is for developers who don’t want to use and adopt any existing libraries because they create a black box in your form validation for React Apps alone.

Form Validation Using Custom React Hooks, Build a form validation engine using custom React Hooks, from scratch, without having to learn a single form library. Read on to learn how! react-datepicker provides onChangeRaw property to get raw (typed) value inside the datePicker. In order to restrict or validate the datepicker input field we need the raw value which is not available on onChange event of the datepicker component.

Form Validation in React.js - Part 11, My new approach to form validation of React components only requires a My implementation only allows one error per field to be reported. Tutorial built with React 16.7 and Webpack 4.29. Other versions available: In this tutorial we'll go through an example of how you can implement role based authorization / access control using React. The example builds on another tutorial I posted recently which focuses on JWT authentication in React + Redux, in this version I've removed redux

Comments
  • Maybe that could help. stackoverflow.com/questions/41296668/…
  • thanks for your answer. Could you also show me the regex file which you have imported in the validation module
  • @Niklas That's just a email regula expression. export const emailRegex = /^(([^<>()[]\\.,;:\s@\"]+(\.[^<>()[]\\.,;:\s@\"]+)*)|(\".+\"))@(([[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
  • i implemente the Code in the SandBox.io Project, but i get any issues. Please, could you look at the Project to help me to solve the issues? Here is the link: codesandbox.io/s/wozl0qmw6w - thanks a lot
  • @Niklas You're not even setting the input values in react state. And also you're using error object as input values.
  • thanks for your answer. I updated the SandBox Project. But the ErrorMessages will not be shown? Where is my mistake. Could you help me again, please?