0

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.

enter image description here

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:

Edit wozl0qmw6w

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.

madhurgarg
  • 1,301
  • 2
  • 11
  • 17
Niklas
  • 1,638
  • 4
  • 19
  • 48
  • Maybe that could help. https://stackoverflow.com/questions/41296668/reactjs-form-input-validation/41297611#41297611 – Boky Sep 18 '18 at 10:08

3 Answers3

1

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>
  )
}
Bill
  • 17,872
  • 19
  • 83
  • 131
0

EDIT: As suggested by @bill I have personally used react-hook-form and I think it's great in terms of developer experience and simplicity. I would recommend using it.

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.

madhurgarg
  • 1,301
  • 2
  • 11
  • 17
  • thanks for your answer. Could you also show me the regex file which you have imported in the validation module – Niklas Sep 18 '18 at 10:31
  • @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,}))$/ – madhurgarg Sep 18 '18 at 12:02
  • 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: https://codesandbox.io/s/wozl0qmw6w - thanks a lot – Niklas Sep 18 '18 at 13:00
  • @Niklas You're not even setting the input values in react state. And also you're using error object as input values. – madhurgarg Sep 18 '18 at 13:21
  • 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? – Niklas Sep 18 '18 at 13:54
0

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/

azrahel
  • 1,143
  • 2
  • 13
  • 31