首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >响应本机Formik / Yup验证不会引发错误

响应本机Formik / Yup验证不会引发错误
EN

Stack Overflow用户
提问于 2022-09-05 07:33:47
回答 1查看 123关注 0票数 3

我已经尝试了3天的时间来进行数组验证,使用Formik和。验证是有效的,但我无法理解如何显示错误。

我在api中有很多任务,如果开关是假的,用户需要写一个注释,为了测试目的,我禁用了这个开关,以了解如何让数组验证运行。

TaskScreen:

代码语言:javascript
运行
复制
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;

任务组件

代码语言:javascript
运行
复制
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;

我也有问题,console.log的Formik包,无法解决,这是我的第一步与RN,抱歉,如果问题是无聊的。

提前感谢您的任何帮助。

EN

回答 1

Stack Overflow用户

发布于 2022-09-07 07:48:34

正如这里提到的,在验证文档中,您应该创建一个回调,作为Formik组件的一个子元素,该组件有一个对象,它与两个params组合在一起,这两个参数是errors和map of field names to **whether** the field has been touched:这些错误是表单的validation errors,所触及的是map of field names to **whether** the field has been touched。请参阅Formik提供的这个样本

代码语言:javascript
运行
复制
     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>
 );
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73605929

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档