Skip to content
Advertisement

How to show validation error in form in react js?

I have created a form and connected it to server.

 <form>
        <h2>Create Account</h2>

        <fieldset>
          <label for="name">Username</label>
          <input
            onChange={(e) => handle(e)}
            value={data.name}
            type="text"
            id="name"
            name="name"
          />

          <label for="email">Email</label>
          <input
            onChange={(e) => handle(e)}
            value={data.email}
            type="email"
            id="email"
            name="email"
          />

          <label for="password">Password</label>
          <input
            onChange={(e) => handle(e)}
            value={data.password}
            type="text"
            id="password"
            name="password"
          />
          <label for="confirmPassword">Confirm Password</label>
          <input
            onChange={(e) => handle(e)}
            value={data.confirmPassword}
            type="text"
            id="confirmPassword"
            name="confirmPassword"
          />
        </fieldset>
        <button type="submit" onClick={(e) => sendData(e)}>
          Create Account
        </button>
      </form>

In case of validation error response is like this “message”: “ValidationError: confirmPassword: Confirm Password did not match

By regular expression I can pic up the error from this message e.g. “Confirm password did not match“.

I don’t know how to show this error below respective input field ?

Advertisement

Answer

  1. In reducer, you should create the validation function
const reducer = combineReducers({
  form: formReducer.validation({
    loginValidation: loginValidation,
  })
})

const loginValidation = values => {
  const errors = {}
  if (!values.email) {
    errors.email = 'Required'
  } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$/i.test(values.email)) {
    errors.email = 'Invalid email address'
  }

  if (!values.password) {
    errors.age = 'Required'
  }

  if (!values.confirmPassword) {
    errors.age = 'Required'
  }

  if (values.confirmPassword !== values.password) {
    errors.age = 'Confirm Password did not match'
  } 
  return errors
}
  1. In form component, you should do sth like
<div>
  <label>Email</label>
  <Field name="email" component={email =>
     <div>
      <input type="text" {...email} placeholder="Email"/>
      {email.touched && email.error && <span>{email.error}</span>}
     </div>
    }/>
      </div>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement