Formik 和 Yup 条件验证不适用于 useState

Formik and Yup conditional validation not working with useState

我正在将 React Native 与 Expo 结合使用,目前正在 IOS 工作。

使用 Formik 和 Yup,我正在尝试有条件地验证表单,

这是form.js

import {Formik} from 'formik'
import { newApptSchema } from '../FormValidation'

const NewAppt = ({ navigation }) => {

    
    //These are the values that formik and yup will check
    const apptForm = {
        
        firstName: '',
        lastName: '',
        
        spouseFirstName: '',
        spouseLastName: '',
        
        etc...
    }
const [hasSpouse, sethasSpouse] = useState(false);

return (
            <Formik
                //Prevents a dumb glitch
                enableReinitialize
                //validates based on the Form Validation Schema
                validationSchema={newApptSchema}
                initialValues={apptForm}
                //Prevents Errors from popping up as they type
                validateOnChange={false}
                onSubmit={(values, actions)=>(
                    console.log(SubmitNewAppt()),
                    SubmitNewAppt(values),
                    navigation.navigate('Appointments')
                )}
            >
            {(props)=> (
            <>
            <Text style={styles.lableText}>Do you have a Spouse?</Text>
            <Switch 
                    onValueChange={toggleSwitch}
                    value={hasSpouse}
                    />
            { hasSpouse ? <>
                    <View style={{flexDirection:'row'}}>
                        <View style={{flex:1}}>
                            <TextInput  
                            value={props.values.spouseFirstName}
                            placeholder='Spouse First Name'
                            onChangeText={props.handleChange('spouseFirstName')}/> 
                        </View>
                        <View style={{flex:1}}>
                            <TextInput 
                            value={props.values.spouseLastName} 
                            placeholder='Spouse Last Name'
                            onChangeText={props.handleChange('spouseLastName')}> 
                        </View>
                    </View>
                    { props.errors.spouseFirstName || props.errors.spouseLastName ? <View style={{flexDirection:'row'}}>
                        <View style={{flex:1}}>
                            <Text style={styles.errorText}>Test</Text>
                        </View>
                        <View style={{flex:1}}>
                            <Text style={styles.errorText}>{ props.errors.spouseLastName }</Text>
                        </View>
                    </View> : null }
                    </>: null}
            </>
            )}
            </Formik>
    )
}

export default NewAppt

这是我的 FormValidation.js

import * as Yup from 'yup'


//This file is used for all form validations across the app

//exporting the validation schemas to be used in formik forms across the app
export const newApptSchema = Yup.object({
    hasSpouse: Yup.boolean(),
    spouseFirstName: Yup.string()
        .when("hasSpouse", {
        is: true,
        then: Yup.string()
        .required("First Name is required")
        .min(3, '3 Character Min')
    }),
    spouseLastName: Yup.string()
    .when("hasSpouse", {
        is: true,
        then: Yup.string()
        .required("Last Name is required")
        .min(3, '3 Character Min')
    }),
    Phone2: Yup.string()
    .when("hasSpouse", {
        is: true,
        then: Yup.string()
        .matches('^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$', 'Phone number is not valid')
    })
})

当“hasSpouse”为真时,它应该需要 spouseFirstName 和 spouseLastName,并验证 Phone2,但出于某种原因,即使切换了 hasSpouse,它也会在没有这些的情况下通过 'True'。它也不会抛出预期的错误。

我进入了 Yup git 和 NPM 页面,但找不到 .when 的文档,我只是通过 Stack 了解它。

我想我遗漏了一些愚蠢的东西,不知何故 'hasSpouse' 在验证模式中是错误的,但我不知所措。

如有任何帮助,我们将不胜感激。

更改 Switch 值不会影响 Formik 的 hasSpouse 值。

重构代码如下

<Switch
  onValueChange={(value) => {
    props.setFieldValue("hasSpouse", value);
  }}
  value={props.values.hasSpouse}
/>;