【发布时间】:2020-04-24 14:08:54
【问题描述】:
我有一个为所有字段设置了验证的表单。对于验证,我检查每个输入值是否为required,是否具有所需的max length 和min length。完成后,我会进行最后检查,看看整个表格是否有效。
上述验证适用于用户在输入字段中实际键入的字段(这就是我所遵循的教程所说的方法)。但是我修改了Country 输入字段和Email 输入字段,以便它们被预先填写。 Country 包含England,UK 的默认字符串,并且电子邮件字段预填充了用户从this.props.email 状态注册时填写的电子邮件。现在,如果我在预填充数据旁边的这两个字段中输入一些内容,我的表单只会返回为 valid。经过数小时的调试后,我看不出为什么...
见下面的代码:
state = {
orderForm: {
name: {
elementType: "input",
elementConfig: {
type: "text",
placeholder: "Your Name"
},
value: "",
validation: {
required: true
},
valid: false,
touched: false
},
postCode: {
elementType: "input",
elementConfig: {
type: "text",
placeholder: "PostCode"
},
value: "",
validation: {
required: true,
minLength: 5,
maxLength: 8
},
valid: false,
touched: false
},
country: {
elementType: "input",
elementConfig: {
type: "text",
placeholder: "Country"
},
value: "England, UK",
validation: {
required: true
},
valid: false,
touched: false
},
email: {
elementType: "input",
elementConfig: {
type: "email",
placeholder: "Your E-Mail"
},
value: this.props.email,
validation: {
required: true
},
valid: false
},
formIsValid: false
};
inputChangedHandler = (event, inputIdentifier) => {
const updatedOrderForm = {
...this.state.orderForm
};
const updatedFormElement = {
...updatedOrderForm[inputIdentifier]
};
updatedFormElement.value = event.target.value;
updatedFormElement.valid = checkValidity(
updatedFormElement.value,
updatedFormElement.validation
);
updatedFormElement.touched = true; // ensures that the user types something in the input field
updatedOrderForm[inputIdentifier] = updatedFormElement;
let formIsValid = true;
for (let inputIdentifier in updatedOrderForm) {
formIsValid = updatedOrderForm[inputIdentifier].valid && formIsValid;
}
this.setState({ orderForm: updatedOrderForm, formIsValid: formIsValid });
};
render() {
const formElementsArray = [];
for (let key in this.state.orderForm) {
formElementsArray.push({
id: key,
config: this.state.orderForm[key]
});
}
let form = (
<form>
{formElementsArray.map(formElement => {
return (
<Input
inputtype={formElement.config.elementType}
key={formElement.id}
elementType={formElement.config.elementType}
elementConfig={formElement.config.elementConfig}
value={formElement.config.value}
invalid={!formElement.config.valid}
shouldValidate={formElement.config.validation}
touched={formElement.config.touched}
changed={event =>
this.inputChangedHandler(
event,
formElement.id,
formElement.config.value
)
}
/>
);
})}
<Button
clicked={this.orderHandler}
btnType="Success"
disabled={!this.state.formIsValid}
>
PLACE ORDER HERE
</Button>
</form>
);```
validation function
export const checkValidity = (value, validation) => {
let isValid = true;
if (validation.required) {
isValid = value.trim() !== "" && isValid;
}
if (validation.minLength) {
isValid = value.length >= validation.minLength && isValid;
}
if (validation.maxLength) {
isValid = value.length <= validation.maxLength && isValid;
}
return isValid;
};
【问题讨论】:
标签: javascript reactjs forms validation