繁体   English   中英

Formik 验证模式阻止调用 onSubmit 方法

[英]Formik Validation Schema preventing onSubmit method to be called

这是我第一次使用 Formik,我正在尝试使用它来验证用户注册表。 这是我的代码:

interface Props { }

export interface RegisterData {
    name: string;
    email: string;
    password: string;
    status?: boolean
}

const validationSchema: SchemaOf<RegisterData> = yup.object().shape({
    name: yup
        .string()
        .max(20, "Name cannot be more than 20 characters")
        .required("name is required"),
    email: yup
        .string()
        .email("Enter a valid email")
        .required("Email is required"),
    password: yup
        .string()
        .min(8, "Password should be of minimum 8 characters")
        .required("Password is required"),
    status: yup
        .boolean()
        .notRequired()
});

const Create: React.FC<Props> = () => {
    const dispatch = useAppDispatch();
    const theme = useTheme();
    const navigate = useNavigate();
    const [checked, setChecked] = useState<boolean>(false);

    const initialFormValues: RegisterData = {
        name: "",
        email: "",
        password: ""
    }

    const handleChecked = (event: any) => {
        console.log(event.target.checked);
        setChecked(event.target.checked);
    }

    const handleSubmit = async (values: any) => {
        console.log("hello");
        console.log(values);
        
    }

    const formik = useFormik({
        initialValues: initialFormValues,
        validationSchema: validationSchema,
        onSubmit: handleSubmit
    })

    return (
        <Box
            ...
                <Box component="form" onSubmit={formik.handleSubmit} sx={{ mt: 2 }}>
                    <Grid container spacing={1}>
                        <Grid item xs={12}>
                            <Typography
                                variant="subtitle1"
                                sx={{
                                    color: theme.palette.text.secondary
                                }}
                            >
                                {Constants.Create.NAME_HEADER}
                            </Typography>
                        </Grid>
                        <Grid item xs={12}>
                            <TextField
                                margin="normal"
                                required
                                fullWidth
                                id="name"
                                name="name"
                                label="Required"
                                variant="filled"
                                size="small"
                                sx={{
                                    marginTop: "0px"
                                }}
                            />
                        </Grid>
                        <Grid item xs={12}>
                            <Typography
                                variant="subtitle1"
                                sx={{
                                    color: theme.palette.text.secondary
                                }}
                            >
                                {Constants.Create.EMAIL_HEADER}
                            </Typography>
                        </Grid>
                        <Grid item xs={12}>
                            <TextField
                                margin="normal"
                                required
                                fullWidth
                                id="email"
                                name="email"
                                label="Required"
                                variant="filled"
                                size="small"
                                sx={{
                                    marginTop: "0px"
                                }}
                            />
                        </Grid>
                        <Grid item xs={12}>
                            <Typography
                                variant="subtitle1"
                                sx={{
                                    color: theme.palette.text.secondary
                                }}
                            >
                                {Constants.Create.PASSWORD_HEADER}
                            </Typography>
                        </Grid>
                        <Grid item xs={12}>
                            <TextField
                                type="password"
                                margin="normal"
                                required
                                fullWidth
                                id="password"
                                name="password"
                                label="Required"
                                variant="filled"
                                size="small"
                                sx={{
                                    marginTop: "0px"
                                }}
                            />
                        </Grid>
                    </Grid>
                    <Button
                        type="submit"
                        fullWidth
                        variant="contained"
                        size="large"
                        sx={{ mt: 2, mb: 2 }}
                    >
                        {Constants.Create.CREATE_ACCOUNT}
                    </Button>
                </Box>
        </Box >
    )
}

当我单击我的提交按钮并调用 handleSubmit 时,没有任何反应,我也没有看到hellovalues被打印到控制台。 但是,当我从useFormik中删除validationSchema时,我可以获得输出。

为什么会这样? 如何将schemaValidation添加到 Formik?

我想问题可能是您没有控制字段的 state。 当您单击提交按钮时,没有任何反应,因为输入元素已更新为不受控制的值。

解决方案是在每个字段上添加指向 formik values state 的valueonChange属性以及handleChange方法。

您还可以将disabled属性添加到传递给它的按钮disabled={formik.isValid || formik.isSubmitting} disabled={formik.isValid || formik.isSubmitting}以动态查看表单的 state。 这里有更多关于 formik API 的信息https://formik.org/docs/api/formik#handlechange-e-reactchangeventany--void

例子:

<TextField
     value={formik.values.password}
     onChange={formik.handleChange}
     ...your other props
 />

此外,仅供参考,将initialFormValues object 放在 function 组件主体之外,您无需在每次重新渲染时重新创建它。

暂无
暂无

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

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