嗨,我又和Yup在一起了
我需要使用Yup验证Fromik字段数组--我的字段如下
[{startdate:'',endDate:'',name:''},{startdate:'',endDate:'',name:''}]开始/结束日期是使用Yup和formik之前的日期对象,我正在进行验证以检查所选日期,这些日期已经退出如下
const checkDate=(selectedDate)=>{
const isExisting = datas
.filter((data) => data.startDate !== null || data.endDate !== null)
.some(
(data) =>
new Date(data.startDate).toLocaleDateString() === selectedDate ||
new Date(data.endDate).toLocaleDateString() === selectedDate,
);
if (isExisting) {
toast.error('Date already exits');
return false;
}
}我知道这有点奇怪。在使用了formik和Yup之后,您中的一些人可能有更好的选择,在使用了formik和Yup之后,可以手动完成所有的表单验证。
说到这里,我需要验证用户选择的日期(如果用户选择了任何日期),验证所选日期是否在数组中存在。
export const CheckoutSchema = Yup.object().shape({
Checkout: Yup.array()
.of(
Yup.object().shape({
name: Yup.string().required(),
startDate: Yup.date().required(),
endDate: Yup.date().required(),
}),
)
});我已经检查了一些git页面和堆栈溢出,但我不知道它在我的情况下是否有效,here
发布于 2020-04-30 04:12:31
我有一个类似的问题,并发现联系的答案有帮助,但没有解释它如何工作。我想出了办法,希望这会更有帮助。
Yup.addMethod(Yup.array, "unique", function(message) {
return this.test("unique", message, function(list) {
const mapper = x => x.name;
const set = [...new Set(list.map(mapper))];
const isUnique = list.length === set.length;
if (isUnique) {
return true;
}
const idx = list.findIndex((l, i) => mapper(l) !== set[i]);
return this.createError({
path: `[${idx}].name`,
message: message,
});
});
});
const MySchema = Yup.object().shape({
Checkout: Yup.array()
.of(
Yup.object().shape({
name: Yup.string().required("Required"),
})
)
.unique("Must be unique"),
});编辑:这实际上会在特定的字段中创建错误消息,我发现它对用户更友好。此外,这只是检查name字段的唯一性,并假定formik中的字段名为${index}.name。
由于我没有测试上面的内容,下面是我的实际代码,数组中有嵌套的对象。这一点我已经测试并证实是有效的。
Yup.addMethod(Yup.array, "unique", function(message, path) {
return this.test("unique", message, function(list) {
const mapper = x => x.description && x.description.number;
const set = [...new Set(list.map(mapper))];
const isUnique = list.length === set.length;
if (isUnique) {
return true;
}
const idx = list.findIndex((l, i) => mapper(l) !== set[i]);
return this.createError({
path: `tests[${idx}].description`,
message: message,
});
});
});
const TestSchema = Yup.object().shape({
tests: Yup.array()
.of(
Yup.object().shape({
description: Yup.object().required("Required"),
})
)
.unique("Test already added above"),
});https://stackoverflow.com/questions/61170893
复制相似问题