简体   繁体   English

React Native Formik / Yup Array Validation 不会引发错误

[英]React Native Formik / Yup Array Validation throws no errors

i was trying for 3 days now to get array validation working with Formik and Yup in React Native with a FieldArray.我现在尝试了 3 天,以便在带有 FieldArray 的 React Native 中使用 Formik 和 Yup 进行数组验证。 The Validation was working but i can't get it how to display the errors.验证正在工作,但我不知道如何显示错误。

I have many tasks from the api where the user needs to write a comment if the switch is false, for testing purposes i disabled the switch to find out how to get the array validation running.我有许多来自 api 的任务,如果开关为假,用户需要在其中写评论,出于测试目的,我禁用了开关以了解如何运行阵列验证。

The TaskScreen:任务屏幕:

import React, { useState } from 'react';
import { StyleSheet, Button } from 'react-native';
import * as yup from 'yup';
import { Formik } from 'formik';

import {  SubmitButton, Tasks } from "../components/forms";

const validationSchema = yup.object().shape({
  tasks: yup.array().of(yup.object().shape({comment: yup.string().required('Required'),})),
});

function TasksScreen({ navigation: { navigate }, route}) {

  const [tasks, setTasks] = useState(route.params.tasks);
  const handleSubmit = async (values) => {
    console.log(values);  
  };
  
  return  (
    <>
      <Formik
          initialValues={{ tasks:  [] }}
          onSubmit={handleSubmit}
          validationSchema={validationSchema}
      >
          <Tasks name="tasks" tasks={tasks} />
          <SubmitButton title="Send" />
      </Formik>
      <Button onPress={() => navigate('TaskLists') } title="Back"/>
    </>
  )

}

const styles = StyleSheet.create({
  container: {},
});

export default TasksScreen;

The Tasks Component任务组件

import React from 'react';
import { useFormikContext, FieldArray } from "formik";
import ErrorMessage from "./ErrorMessage";
import { TextInput, Text, View, StyleSheet, Switch } from 'react-native';

function Tasks({ tasks, name }) {

const {
  setFieldTouched,
  setFieldValue,
  errors,
  touched,
  values,
} = useFormikContext();

return (

    <FieldArray name={name}>
      <>
        { tasks.map((task, key)=>{
          return (
              <>
            <View key={key}>
              <Text>{task.name} {`${name}[${key}].comment]`}</Text>
              <TextInput
                  onBlur={() => setFieldTouched(`${name}[${key}].comment`)}
                  onChangeText={(text) => setFieldValue(`${name}[${key}].comment`, text)}
                  value={values[`${name}[${key}].comment`]}
                  name={`${name}[${key}].comment`}
                  placeholder="Task comment please"
                />
              <ErrorMessage error={`${errors}${name}[${key}].comment`} visible={`${touched}${name}[${key}].comment`} />
            </View>
            </>
          )
        })}
    </>
  </FieldArray> 
);
}

const styles = StyleSheet.create({
container: {},
});

export default Tasks;

I also have problems to console.log the Formik Bag, can't figure it out, it's my first steps with RN, sorry if the question is boring.我也有问题要控制台记录 Formik 包,无法弄清楚,这是我与 RN 的第一步,如果问题很无聊,对不起。

Thanks in advance for any kind of help.提前感谢您的任何帮助。

As mentioned here in the validation docs you should create a callback as a child of the Formik component which has an object combined with two params which are errors and touched: the errors are the validation errors of the forms and the touched is map of field names to **whether** the field has been touched .验证文档中所述,您应该将回调创建为 Formik 组件的子组件,该组件具有 object 以及两个错误和触及的参数:错误是 forms 的validation errors ,而触及的是map of field names to **whether** the field has been touched的 Z1D78DC8ED5121449018B511FE map of field names to **whether** the field has been touched See this Sample provide by the Formik Docs.请参阅 Formik Docs 提供的此示例

     import React from 'react';
 import { Formik, Form, Field } from 'formik';
 import * as Yup from 'yup';
 
 const SignupSchema = Yup.object().shape({
   firstName: Yup.string()
     .min(2, 'Too Short!')
     .max(50, 'Too Long!')
     .required('Required'),
   lastName: 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={{
         firstName: '',
         lastName: '',
         email: '',
       }}
       validationSchema={SignupSchema}
       onSubmit={values => {
         // same shape as initial values
         console.log(values);
       }}
     >
       {({ errors, touched }) => (
         <Form>
           <Field name="firstName" />
           {errors.firstName && touched.firstName ? (
             <div>{errors.firstName}</div>
           ) : null}
           <Field name="lastName" />
           {errors.lastName && touched.lastName ? (
             <div>{errors.lastName}</div>
           ) : null}
           <Field name="email" type="email" />
           {errors.email && touched.email ? <div>{errors.email}</div> : null}
           <button type="submit">Submit</button>
         </Form>
       )}
     </Formik>
   </div>
 );

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

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