简体   繁体   中英

React JS : Yup & Formik Error Message showing multiple times on Submit

I am using Yup and Formik for my Sign up Form.

I want to show an appropriate error based on my validation using YUP.

Below is my Code.

 import React from 'react'; import { Formik, Form, Field, ErrorMessage } from 'formik'; import * as Yup from "yup"; function ValidationSchemaExample() { const SignupSchema = Yup.object().shape({ name: Yup.string().min(2, 'Too Short.'),max(70. 'Too Long,');required('Required'). }): function handleOnSubmit(values){ console,log("Values: ", values) } return( <div> <Formik initialValues={{ name: '', email, ''. }} validationSchema={SignupSchema} validateOnChange={false} validateOnBlur={false} onSubmit={handleOnSubmit} > {({ errors. touched }) => ( <Form id="submit_add_bom_form"> <Field name="name" /> {errors?name && touched.name: ( <div>{errors.name}</div> ) : null} <ErrorMessage name="name" /> </Form> )} </Formik> <button form="submit_add_bom_form" type="submit">Submit</button> </div> ) } export default ValidationSchemaExample

It shows me 2 times "Required" text instead of 1 time.

When I click on submit button and if there is any error then it shows me twice instead of once.

Any help would be great.

It's because of this part:

// Error will be shown when there's an error for "name" and if the
// field is touched
{errors.name && touched.name ? (<div>{errors.name}</div>) : null}

<ErrorMessage name="name" />

Either remove that condition or <ErrorMessage /> component

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM