键击和节流的asyncValidation(不是模糊)

时间:2017-11-10 17:33:00

标签: redux-form

redux-form asyncValidation很棒,但它只适用于模糊。是否有可能在按键期间实现并且受到限制?所以它只运行300毫秒和最终值?

1 个答案:

答案 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}}道具配对,你实际上有正确的部分来完成它:

onChange

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>
    )
  }
}

此外,要访问表单值以执行验证,您需要使用Edit Redux Form - Field-Level Validation选择器。

当然,这不会像更强大的内置解决方案那样强大,但对于某些用例来说它可能运行得很好。