Gee*_*bhu 5 javascript ecmascript-6 reactjs yup formik
我withFormik()在React应用程序中使用的表单具有此验证模式,这validateJql()是我的自定义验证功能yup
validationSchema: Yup.object().shape({
rework: Yup.string().required("Rework query is required").validateJql(),
originalEstimate: Yup.string().required("Original Estimate query is required").validateJql()
})
Run Code Online (Sandbox Code Playgroud)
我的表单组件是这样的:
const addSomeForm = (props) => {
const {
values,
touched,
errors,
isSubmitting,
handleChange,
handleSubmit,
} = props;
return (
<form onSubmit={handleSubmit}>
<div className="form-group">
<div>
<label htmlFor="name" className="col-form-label"><b>Rework Query:</b></label>
<textarea id="query.rework" rows="5" type="text" className="form-control" placeholder="Enter JQL with aggregate Function" value={values.query.rework} onChange={handleChange} required />
{errors.query && errors.query.rework && touched.query && <span className="alert label"> <strong>{errors.query.rework}</strong></span>}
</div>
</div>
<div className="form-group">
<div>
<label htmlFor="name" className="col-form-label"><b>Original Estimate:</b></label>
<textarea id="query.originalEstimate" rows="5" type="text" className="form-control" placeholder="Enter JQL with aggregate Function" value={values.query.originalEstimate} onChange={handleChange} required />
{errors.query && errors.query.originalEstimate && touched.query && <span className="alert label"> <strong>{errors.query.originalEstimate}</strong></span>}
</div>
</div>
</form>
)
Run Code Online (Sandbox Code Playgroud)
现在,我想要做的是不是对的形式运行验证提交如果该字段rework并originalEstimate没有被触及,也没有空。如何使用withFormikHOC或实现此目的Yup?我已经部分浏览过Yupdocs和Formikdocs,但是找不到适合我的问题的东西。
在提交一次表单并对其进行编辑之后,可以对其中的多个字段中的一些细微调整进行修改。如果有多个字段并且仅编辑了一些字段,则我不想对所有存在的字段进行验证。
先感谢您。
这是formik 文档中所述的默认所需行为,但我认为您可以执行以下操作:
不使用validationSchema,而使用validate函数。
验证函数的工作方式与验证模式的工作方式相同。您只需要从具有mix.validate 的函数中以编程方式使用 Yup
所以你可以完全控制表单中的所有道具。您还可以使用getFieldMeta来获取字段的触摸值和值,并在验证中使用它。touched或者从对象中获取这些道具getIn
就像是:
// Some util functions
function mapYupErrorsToFormikErrors(err: { inner: any[] }) {
return err.inner
.filter((i: { path: any }) => !!i.path)
.reduce(
(curr: any, next: { path: any; errors: any[] }) => ({
...curr,
[next.path]: next.errors[0],
}),
{},
)
}
function validateSchema(values: object, schema: Schema<object>) {
return schema
.validate(values, {
abortEarly: false,
strict: false,
})
.then(() => {
return {}
})
.catch(mapYupErrorsToFormikErrors)
}
// Your validation function, as you are using `withFormik` you will have the props present
function validateFoo(values, props) {
const { touched, value } = props.getFieldMeta('fooFieldName') // (or props.form.getFieldmeta, not sure)
const errors = validateSchema(values, yourYupSchema)
if (!touched && !value && errors.fooFieldName) {
delete errors.fooFieldName
}
return errors
}
Run Code Online (Sandbox Code Playgroud)
好吧,touched 可能不适用于您的用例,因为 formik 可能会在提交时将其设置为 true,但是您拥有所有道具,并且可以使用不同的东西,例如空值或您手动设置的其他状态道具。你在那里得到了所有的控制权。
| 归档时间: |
|
| 查看次数: |
838 次 |
| 最近记录: |