我有一个登录表单。我试图在React中验证它。在表单标记上的OnSubmit,它调用handleSubmit()。然后,此函数调用validateField(),该函数调用validateForm()。全部看看formValid是否为真。当我输入正确的电子邮件和密码格式并单击“提交”时,它将返回false。我再试一次,它回来了。
我第三次点击提交,表格有效并提交表达。为什么它不能立即识别状态变化以形成有效,如何更好地做出反应验证?
谢谢你们一堆
StateRepository
答案 0 :(得分:0)
您可以设置状态' formValid'在' validateField()'仅起作用而不是使用全新的功能。
validateField() {
let fieldValidationErrors = this.state.formErrors;
let emailValid = this.state.emailValid;
let passwordValid = this.state.passwordValid;
emailValid = this.state.email.match(/^([\w.%+-]+)@([\w-]+\.)+([\w]{0,})$/i);
fieldValidationErrors.email = emailValid ? '' : 'email is invalid';
passwordValid = this.state.password.length >= 6;
fieldValidationErrors.password = passwordValid ? '': ' password is too short';
this.setState({
formErrors: fieldValidationErrors,
emailValid: emailValid,
passwordValid: passwordValid
}, () => this.setState({formValid: this.state.emailValid && this.state.passwordValid}));
}
答案 1 :(得分:0)
尝试如下所述: 1)npm install validator&然后在你的组件中进行如下操作或制作单独的组件(即Singup.jsx)并导入当前组件,即 从'./Singup'导入validateSignup;
import Validator from 'validator';
import isEmpty from 'lodash/isEmpty';
export default function validateInput(data) {
let errors = {};
if (!Validator.isEmail(data.email)) {
errors.email = 'Email is required';
}
if (Validator.isNull(data.password)) {
errors.password = 'This field is required';
}
if (Validator.isNull(data.passwordConfirmation)) {
errors.passwordConfirmation = 'This field is required';
}
return {
errors,
isValid: isEmpty(errors)
}
}