下面以redux形式执行基于json的验证的问题
**json creating dynamic form**
const simplefield = [
{
name: "firstname",
type: "text",
placeholder: "Enter Name",
isrequired: "true",
maxLength: "5",
minLength: "3",
checkrules: {
requiredfield: { message: "required firstname" },
maxlength: { value: 5, message: "maxlength" },
minlength: { value: 3, message: "minlength" }
}
},
{ name: "age", type: "number", placeholder: "Enter age" },
{
name: "email",
type: "email",
placeholder: "Enter Email",
checkrules: {
requiredfield: { message: "required" },
},
defaultValue: "email@email.com"
},
]
验证码
const validate = (values, props) => {
const validation = props.fields.filter(field => field.checkrules);
const error = {};
validation.map((v, i) => {
if ("requiredfield" in v.checkrules) {
if (values[v.name] === undefined || values[v.name] === "") {
return (error[v.name] = v.checkrules.requiredfield.message);
} else if (!/\S+@\S+\.\S+/.test(values.email)) {
return (error.email = "invalid");
}
}
});
}
这里我正在创建一个基于json的redux表单,它呈现了字段(我能够实现它)但是我在下面的json中基于名为 checkrules 的字段执行动态验证是实现验证的代码,没有正确实现,请提供解决方案
答案 0 :(得分:0)
export const createModalValidation = value => {
const errors = {};
if (!value.rules || !value.rules.length) {
errors.rules = { _error: 'At least one member must be entered' };
} else {
const rulesArrayErrors = [];
value.rules.forEach((member, memberIndex) => {
const ruleErrors = {};
if (!member || !(member.name == 'your_key')) {
here can check any number of condition...
ruleErrors.fact = 'Required';
rulesArrayErrors[memberIndex] = ruleErrors;
}
});
if (rulesArrayErrors.length) {
errors.rules = rulesArrayErrors;
}
}
return errors;
}