Search code examples
formsvalidationreactjsreduxredux-form

How to keep sync validation with Redux-form v6 while implementing custom onBlur?


I have a Field that needs some custom onBlur functionality, but when I implement my functionality, the normal sync validation stops working. I can still see the error getting updated within props.meta.error when I console log with componentDidUpdate, but it doesn't actually show the error.

I've tried tinkering with manually dispatching a 'touch' action, and trying asyncValidation too, but the error field doesn't show up unless I leave the onBlur prop alone.

Is there a way I can implement my own onBlur function, while still retaining the original error validation stuff?

This is the component I'm making:

class PostalCodeTextInput extends React.Component { // eslint-disable-line
  fetchAddressesValid = () => {
    // this.props.async();
    if (this.props.input.value.length > 5) {
      if (!this.props.meta.error) {
        this.props.fetchAddresses(this.props.input.value);
      }
    }
  }

  render() {
    const { helpText, input, label, type, meta: { touched, error } } = this.props;
    const classNames = classnames({
      'text-input': 'text-input',
      'form-group': 'form-group',
      invalid: touched && error,
    });
    return (
      <div className={classNames}>
        <label htmlFor={label}>{label}</label>
        <div>
          <input
            {...input}
            type={type}
            placeholder={label}
            onBlur={this.fetchAddressesValid} // *
          />
          {touched && error && <p className="warning">{error}</p>}
        </div>
        <small><em>{helpText}</em></small>
      </div>
    );
  }
}

And this is the validation that's supposed to apply:

const validate = (values) => { // eslint-disable-line
  const errors = {};

  // NewAddressFields
  if (!values.get('postal_code')) {
    errors.postal_code = 'Required';
  } ...

This is what it looks like when I comment out the line:

// onBlur={this.fetchAddressesValid}

enter image description here

And this is what it looks like when I leave the line in:

onBlur={this.fetchAddressesValid}

enter image description here

How do I get the error message to pop up like in the first picture, while still using my own onBlur function?


Solution

  • Delegate the onBlur when you're done.


    Change

    onBlur={this.fetchAddressesValid}
    

    to

    onBlur={(e) => {
     this.fetchAddressesValid
     input.onBlur(e);
    }}