tcomb-form-native set error dynamically

1.2k views Asked by At

Assume I have login form with the following fields:

const Email = t.refinement(t.String, (str) => {
  const reg = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
  return reg.test(str);
});

const Password = t.refinement(t.String, (str) => {
  return str.length >= 6; // minimum password length should be 6 symbols
});

const Person = t.struct({
  email: Email,
  password: Password,
});

The data user enters into the fields validates and then I send a request to the authentication server and the server validates received data additionally and it turns out that there is no user with such credentials. So it return according response:

{
  success: false,
  data: { password: ['User with such credentials is not found.'] }
}

The question is, how can I set dynamically error to tcomb property? Something like: this.refs.form.getComponent('password').refs.input.addError(someError);
Is it possible?

1

There are 1 answers

0
Hisham On

In case someone is still looking for an answer, binding the "error message" field option to the internal state of the surrounding component should work. For example:



  render() {

    // ... rest of code omitted 

    let formOptions = {
      fields: {
        email: {
          hasError: this.state.emailHasError,
          error: this.state.emailErrorMessage
        }
      }
    };

    return (<Tcomb.form.Form
      ref="myForm"
      options={formOptions}
    />);
  }

And then on receiving server response, you can update the main component state, like:


    this.setState({
          emailHasError: true,
          emailErrorMessage: 'Invalid email address'
        });