validation - 是的,使用动态数据进行验证
问题描述
我对反应钩子表单的 API 响应要求进行了 yup 验证。我的表格是这样的:
import React from "react";
import useForm from "react-hook-form";
import { schema } from "./schema";
import { useTestProps } from "./useTestProps";
function Sub({ title, showForm }) {
const { register, handleSubmit, errors } = useForm({
validationSchema: schema
});
const { data } = useTestProps();
const onSubmit = (data) => {
//submit form
};
// console.log(errors);
return (
<div>
<form onSubmit={handleSubmit(onSubmit)}>
<label>{title}</label>
<input type="text" name="iip" ref={register} />
<br />
{errors.iip && <p>{errors.iip.message}</p>}
<br />
<label>Email</label>
<input type="text" name="email" ref={register} />
<br />
{errors.email && <p>{errors.email.message}</p>}
<br />
<input type="submit" />
</form>
</div>
);
}
export default Sub;
表单的验证模式是这样的,
//schema.js
import * as yup from "yup";
export const schema = yup.object().shape({
iip: yup
.string()
.required()
.test("validate with testProps", "iip not found", (value) => {
// validate that value should be one of testProps
// if value is in data, return true, or return false
return true
}),
email: yup.string().email().required()
});
我的要求是使用从useTestProps中的 API 调用返回的数据验证iip字段, 如下所示,
{
"data": ["test1", "test2", "test3"]
}
如何访问模式对象测试中的数据,我可以将用户输入的值与 JSON 响应进行比较?
解决方案
推荐阅读
- apache-spark - spark和kafka之间的版本兼容性
- python - 如何获得上一年的中位数价格?
- python - 如何在while循环中记录第一次出现
- python-3.x - 当我在另一个函数中调用一个函数时,返回值不会被打印出来,所以我需要使用 print 函数
- class - Dart:如何访问另一个类中对象的类属性?(嵌套类)
- r - oob=scales::squish 不适用于 ggplot2 中的 scale_size_continuous
- reactjs - 如何隐藏 URL 扩展名以防止访问页面
- ios - 如何使用委托和协议传递数据
- django - 表“avc.consumptions_message”不存在
- unit-testing - 如何将 POST 请求 multipart/form-data 字段作为数组发送以进行单元测试?