vij*_*ode 15 javascript reactjs redux yup formik
我正在尝试在我的反应形式中使用Yupwith Formik。表单字段将是动态的,以便进行验证。
export const formData = [
{
id: "name",
label: "Full name",
placeholder: "Enter full name",
type: "text",
required: true,
value: "User name",
values: [],
validations: [
{
type: "minLength",
value: "5",
error_message: "name should be atleast 5 char long"
},
{
type: "maxLength",
value: "10",
error_message: "name should be atleast 5 char long"
}
]
},
{
id: "email",
label: "Email",
placeholder: "Email",
type: "text",
required: true,
value: "email",
values: [],
validations: [
{
type: "minLength",
value: "5",
error_message: "name should be atleast 5 char long"
},
{
type: "maxLength",
value: "10",
error_message: "name should be atleast 5 char long"
},
{
type: "email",
error_message: "Valid email"
}
]
},
{
id: "phoneNumber",
label: "phone number",
type: "text",
required: true,
value: "7878787878",
values: [],
validations: [
{
type: "minLength",
value: "5",
error_message: "name should be atleast 5 char long"
},
{
type: "maxLength",
value: "10",
error_message: "name should be atleast 5 char long"
},
{
type: "required",
error_message: "phone number is required"
}
]
},
{
id: "total",
label: "Total People in Family",
placeholder: "family members count",
type: "text",
required: false,
value: "1",
values: [],
validations: [
{
type: "minLength",
value: "1",
error_message: "there should be atleast 1 family member"
},
{
type: "maxLength",
value: "5",
error_message: "max family members can be 5"
}
]
}
]
let validateSchema = yup.object().shape({
name: yup.string().required("name is required"),
email: yup.string().email(),
phoneNumber: yup.number().min(10, "minium 10 numbers"),
total: yup
.number()
.min(1, "minium 1 member")
.max(5, "max 5 member")
.required("member is required") });
Run Code Online (Sandbox Code Playgroud)
Yup。我知道你可以像上面的 `validateSchema' 变量一样创建静态 Yup 验证模式。formData.validation数组中的值创建这个验证模式。我在这个codeandbox中尝试了一些方法,
但仍然无法弄清楚。此外,我调查了Yup.lazy但对我来说似乎非常混乱。任何帮助将不胜感激 :)
vij*_*ode 15
以防有人试图动态创建yupschema。在一些帮助下,我能够做到。
import * as yup from "yup";
export function createYupSchema(schema, config) {
const { id, validationType, validations = [] } = config;
if (!yup[validationType]) {
return schema;
}
let validator = yup[validationType]();
validations.forEach(validation => {
const { params, type } = validation;
if (!validator[type]) {
return;
}
console.log(type, params);
validator = validator[type](...params);
});
schema[id] = validator;
return schema;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9860 次 |
| 最近记录: |