简体   繁体   English

Formik + Yup 表单字符串验证不适用于 Material UI TextField +useFormik 或 Formik 组件

[英]Formik + Yup form string validation not working with either Material UI TextField +useFormik or Formik component

I have created a few different versions of a Formik form using different methods to try to get error handling to work properly (specifically, to reject inputs in certain fields if those inputs are not strings).我已经使用不同的方法创建了几个不同版本的 Formik 表单,以尝试使错误处理正常工作(具体来说,如果这些输入不是字符串,则拒绝某些字段中的输入)。 Struggling to see why a non-string isn't getting picked up and throwing an error...努力了解为什么未拾取非字符串并引发错误...

Here's my first attempt, which uses Material UI TextField + useFormik这是我的第一次尝试,它使用 Material UI TextField + useFormik

import { useFormik } from 'formik';
import * as yup from 'yup';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import { IAssetDTO } from '../types/types';

const validationSchema = yup.object({
    id: yup
        .string()
        .min(1, "Please enter id more than 1 character")
        .required("This field is required"),
    name: yup
        .string()
        .min(1, "Please enter name more than 1 character")
        .required("This field is required"),
    tags: yup
        .array()
        .nullable(),
    type: yup
        .string()
        .min(1, "Please enter name more than 1 character")
        .required("This field is required"),
    s3URL: yup
        .string()
        .min(1, "Please enter name more than 1 character")
        .required("This field is required"),
    thumbnailImageURL: yup
        .string()
        .min(1, "Please enter name more than 1 character")
        .required("This field is required"),

});



//create your own upload component 
export const EditAssetForm = (props:IAssetDTO) => {

    const formik = useFormik({
        initialValues: {
            id: props.id,
            name: props.name,
            tags: props.tags,
            type: props.type,
            s3URL: props.s3URL,
            thumbnailImageURL: props.thumbnailImageURL,
            createdAt:props.createdAt,
            updatedAt:props.createdAt

        },
        validationSchema: validationSchema,
        onSubmit: (values) => {
            
            console.log("logging values" +JSON.stringify(values))
    
            alert(JSON.stringify(values, null, 2));
        },
    });

    return (
        <div>
           
            <form onSubmit={formik.handleSubmit}>
                <TextField
                    fullWidth
                    id="id"
                    name="id"
                    label="ID"
                    value={formik.values.id}
                    onChange={formik.handleChange}
                    error={formik.touched.id && Boolean(formik.errors.id)}
                    helperText={formik.touched.id && formik.errors.id}
                />...

Everything renders fine, and the proper error gets thrown for character minimum, and being required.一切都很好,并且为最小字符抛出正确的错误,并且是必需的。 But if I enter a string, no error gets thrown.但是如果我输入一个字符串,不会抛出任何错误。

Here's my second attempt, in which I changed the component to use Formik, Form, and Field with schema validation这是我的第二次尝试,我将组件更改为使用具有模式验证的 Formik、Form 和 Field

import { Formik, Form, Field } from 'formik';
 import * as Yup from 'yup';
 import { IAssetDTO } from '../types/types';
 
 const ValidationSchema = Yup.object().shape({
    id: Yup
    .string()
    .min(25, "Please enter id more than 25 character")
    .required("This field is required"),
name: Yup
    .string()
    .min(1, "Please enter name more than 1 character")
    .required("This field is required"),
tags: Yup
    .array()
    .nullable(),
type: Yup
    .string()
    .min(1, "Please enter name more than 1 character")
    .required("This field is required"),
s3URL: Yup
    .string()
    .min(1, "Please enter name more than 1 character")
    .required("This field is required"),
thumbnailImageURL: Yup
    .string()
    .min(1, "Please enter name more than 1 character")
    .required("This field is required"),
 });
 
 export const NewEditAssetForm = (props:IAssetDTO) => (
   <div>
     <h1>Signup</h1>
     <Formik
       initialValues={{
        id: props.id,
        name: props.name,
        tags: props.tags,
        type: props.type,
        s3URL: props.s3URL,
        thumbnailImageURL: props.thumbnailImageURL,
        createdAt:props.createdAt,
        updatedAt:props.createdAt

    }}
       validationSchema={ValidationSchema}
       onSubmit={values => {
       console.log("logging values" +JSON.stringify(values))
    
        alert(JSON.stringify(values, null, 2));
       }}
     >
       {({ errors, touched }) => (
         <Form>
           <Field name="id" />
           {errors.id && touched.id ? (
             <div>{errors.id}</div>
           ) : null}...

Still no errors get thrown when input value is not a string (when I input a number, for example).当输入值不是字符串时(例如,当我输入数字时)仍然不会抛出任何错误。

I though maybe it is because I am passing props to the form?我虽然可能是因为我正在将道具传递给表格? So I took the props out.所以我把道具拿出来了。

My last attempt used the exact copy and paste of the validation schema example and is not throwing errors when the input is a number.我最后一次尝试使用了验证模式示例的精确复制和粘贴,并且在输入数字时没有抛出错误。

What simple thing am I missing?我错过了什么简单的事情?

Thanks谢谢

For any string validations from Yup, they accept alphanumeric values.对于来自 Yup 的任何字符串验证,它们接受字母数字值。 You would want to explore regex if you wanted letters only (for example a name).如果你只想要字母(例如名字),你会想要探索正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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