0

new to react, just starting to work on a react-redux application. Just wondering does anyone have any tips on best practices relating to form validation and displaying error messages? Any thoughts on this greatly appreciated :)

uidevthing
  • 1,781
  • 2
  • 12
  • 24
  • Looking at redux-form as a possible solution (might be a bit much to start out with though) or else maybe something like material-ui with a custom validator to start with. – uidevthing Jun 08 '18 at 12:57

2 Answers2

0

The react way is to have a container handle the state and pass it through the props to the inputs (components). So it's not really a react-redux thing to handle a validation, if of course you don't build through multiple routes and need that global state.

Norbert
  • 2,741
  • 8
  • 56
  • 111
0

I like using Formik for forms in React. The main benefits are:

  • Validation and error messages
  • Handling forms state
  • Handling form submission

And it is a good idea to use Yup (a schema validator) with Formik.

Here is an example of a form with Formik + Yup:

yarn add formik yup

import React from 'react';
import { Formik, Form, Field } from 'formik';
import * as Yup from 'yup';

const SignupSchema = Yup.object().shape({
  : Yup.string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required('Required'),
  email: Yup.string()
    .email('Invalid email')
    .required('Required'),
});

export const ValidationSchemaExample = () => (
  <div>
    <h1>Signup</h1>
    <Formik
      initialValues={{
        name: '',
        email: '',
      }}
      validationSchema={SignupSchema}
      onSubmit={values => {
        // same shape as initial values
        console.log(values);
      }}
    >
      {({ errors, touched }) => (
        <Form>
          <Field name="name" />
          {errors.name && touched.name ? (
            <div>{errors.name}</div>
          ) : null}
          <Field name="email" type="email" />
          {errors.email && touched.email ? <div>{errors.email}</div> : null}
          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
  </div>
);
Tymoxx
  • 167
  • 2
  • 11