我正在构建一个通用表单组件,我创建了一个字段创建组件,该组件将从json blob生成字段。
我正在尝试集成错误/警告处理-但希望改进代码库。
// validateHander
validateHandler(values) {
console.log("values",values);
console.log("this.props.fields", this.props.fields);
const errors = {}
for (let i = 0; i < this.props.fields.length; ++i) {
let field = this.props.fields[i];
let fieldName = field.name[0];
console.log(field);
if(field.validate !== undefined){
//create validation
if(field.validate.includes("email")) {
//email
if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values[fieldName])) {
errors[fieldName] = 'Invalid email address'
}
}
if(field.validate.includes("minLength")) {
//minLength
if (values[fieldName] !== undefined && values[fieldName].length < 3) {
errors[fieldName] = 'Must be 3 characters or more'
}
}
if(field.validate.includes("required")) {
//required
if (!values[fieldName]) {
errors[fieldName] = 'Required'
}
}
}
}
return errors;
}
values变量是表单当前值的对象,看起来像这样
values {email: "bobbarker2@maryland.com", first_name: "Bob", surname: "Barker"}
道具字段是制作json blob的字段
let fields = [
{
"type": "text",
"label": "Emai",
"name": ["email"],
"options": [],
"validate": ["required", "minLength"]
},
{
"type": "text",
"label": "First Name",
"name": ["first_name"],
"options": [],
"validate": ["required", "minLength"]
},
{
"type": "text",
"label": "Surname",
"name": ["surname"],
"options": [],
"validate": ["required", "minLength"]
},
{
"type": "text",
"label": "Screenname",
"name": ["screenname"],
"options": []
},
{
"type": "text",
"label": "Company",
"name": ["company"],
"options": []
},
{
"type": "text",
"label": "Work Email",
"name": ["work_email"],
"options": []
},
{
"type": "text",
"label": "Contact Number",
"name": ["contact_number"],
"options": []
}
];
这是用于验证的const变量列表-但我不确定如何实现-除了validateHandler中的方式之外
/*
const required = value => (value || typeof value === 'number' ? undefined : 'Required')
const maxLength = max => value =>
value && value.length > max ? `Must be ${max} characters or less` : undefined
const maxLength15 = maxLength(15)
const minLength = min => value =>
value && value.length < min ? `Must be ${min} characters or more` : undefined
const minLength2 = minLength(2)
const number = value =>
value && isNaN(Number(value)) ? 'Must be a number' : undefined
const minValue = min => value =>
value && value < min ? `Must be at least ${min}` : undefined
const minValue13 = minValue(13)
const email = value =>
value && !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)
? 'Invalid email address'
: undefined
const tooYoung = value =>
value && value < 13
? 'You do not meet the minimum age requirement!'
: undefined
const aol = value =>
value && /.+@aol\.com/.test(value)
? 'Really? You still use AOL for your email?'
: undefined
const alphaNumeric = value =>
value && /[^a-zA-Z0-9 ]/i.test(value)
? 'Only alphanumeric characters'
: undefined
const phoneNumber = value =>
value && !/^(0|[1-9][0-9]{9})$/i.test(value)
? 'Invalid phone number, must be 10 digits'
: undefined
*/