redux-form asyncValidation
很棒,但它只适用于模糊。是否有可能在按键期间实现并且受到限制?所以它只运行300毫秒和最终值?
答案 0 :(得分:2)
有可能吗?简短的回答是肯定的。
这很棘手吗?好吧,正如你所提到的那样,asyncValidation
选项的redux-form
仅适用于onBlur
,而你希望它能够工作onChange
。
因此,您可以将此功能分叉并添加到redux-form
中,以便您可以执行此操作:
@reduxForm({
form: 'login',
asyncValidate: validator,
//asyncBlurFields: ['username','password'],
asyncChangeFields: ['username','password'], /* add this new option */
})
对于deboucing部分,你想要以某种方式去除onChange
处理程序而不是验证函数本身,这会带来另一种选择......
redux-form
导出其内部动作创建者,这可能足以将其一起破解。特别是,stopAsyncValidation
动作创建器允许您将字段级异步错误直接传递到表单中。将其与Field
的{{1}}道具配对,你实际上有正确的部分来完成它:
import React from 'react'
import { Field, reduxForm, stopAsyncValidation } from 'redux-form'
import _debounce from 'lodash.debounce'
import renderField from './renderField'
@reduxForm({form: 'debouncedOnChangeValidation'})
class DebouncedOnChangeValidationForm extends React.Component {
customValidate = () => {
const { form, dispatch } = this.props
dispatch(stopAsyncValidation(form, { username: "thats wrong..." })) /* pass in async error directly! */
}
debounceValidate = _debounce(this.customValidate, 1000) /* decorate with debounce! */
render() {
const { handleSubmit, pristine, reset, submitting} = this.props
return (
<form onSubmit={handleSubmit}>
<Field name="username" type="text"
component={renderField} label="Username"
onChange={this.debounceValidate} /* bind validation to onChange! */
/>
<div>
<button type="submit" disabled={submitting}>Submit</button>
<button type="button" disabled={pristine || submitting} onClick={reset}>Clear Values</button>
</div>
</form>
)
}
}
当然,这不会像更强大的内置解决方案那样强大,但对于某些用例来说它可能运行得很好。