[英]How to check if form is valid on submit in react formik
I have used the formik library in my project.我在我的项目中使用了 formik 库。 Also used yup library for form field validations.还使用 yup 库进行表单字段验证。 I want to check whether the form is valid or not before connecting to api on submit method.我想在通过提交方法连接到 api 之前检查表单是否有效。 Below is my code used in my project.下面是我在我的项目中使用的代码。
<Formik
isInitialValid = {false}
initialValues={this.formData}
validationSchema={CRYP_LOGIN_SCHEMA}
onSubmit={this.loginSubmit.bind(this)}>
{({ errors, status, touched, isValid }) => (
<Form className="login_reg_form">
<div className="input_control_wrp mb-4">
<div className="input_control">
<span className="left_icon"><i className="fas fa-user"></i></span>
<Field placeholder="Enter your Email" name="email" />
</div>
{errors.email && touched.email && <span className="mt-1 input_error">{errors.email}</span>}
</div>
<div className="input_control_wrp mb-2">
<div className="input_control">
<span className="left_icon"><i className="fas fa-key"></i></span>
<Field type={this.state.pwdType} placeholder="Enter your Password" name="password" />
<a
onClick={this.togglePwdType.bind(this)}
href="javascript:void(0)"
className="right_icon">
<i className={this.state.pwdType == 'password' ? 'fas fa-eye' : 'fas fa-eye-slash'}></i>
</a>
</div>
{errors.password && touched.password && <span className="mt-1 input_error">{errors.password}</span>}
</div>
<div className="forgot_pwd_link mb-4">
<a href="javascript:void(0)" className="">Forgot password?</a>
</div>
<div className="input_submit">
<button className={ !isValid ? 'disabled_btn' : '' } type="submit">Sign In</button>
</div>
and my method used on submit event is below:我在提交事件上使用的方法如下:
loginSubmit(values,formikBag) {
console.log('formikBag',formikBag);
}
I want to check if the form is valid or invalid inside the above method.我想在上述方法中检查表单是否有效。
Kindly, provide solution to accomplish it.请提供解决方案来完成它。 Thanks in advance.提前致谢。
A quick solution where you do not have to validate the form on submitting is to set the initialErrors
property to the Initial Values ( initialErrors ={InitialValues}
) and use the isValid
value to enable the Submit button, also be sure that you mark your required field as required in your Yup schema validation ( email: Yup.string().label('Email').email().required()
).您不必在提交时验证表单的快速解决方案是将initialErrors
属性设置为初始值( initialErrors ={InitialValues}
)并使用isValid
值启用提交按钮,同时确保标记您需要您的email: Yup.string().label('Email').email().required()
架构验证中需要的字段( email: Yup.string().label('Email').email().required()
)。
I'm using the version "formik": "^2.1.4"
我正在使用版本"formik": "^2.1.4"
Note : This is just one approach of many注意:这只是许多方法中的一种
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.