gcanti / tcomb-form

Forms library for react
https://gcanti.github.io/tcomb-form
MIT License
1.16k stars 136 forks source link

Question about setting error state #234

Closed benmonro closed 8 years ago

benmonro commented 8 years ago

I'm using tcomb-form & tcomb-validation to isomorphically validate my data on both client & server (respectively). I'm curious however, is there any way to set the state tcomb-form's errors without actually calling validate()? I have received the error message from the server (which has the ValidationResult as returned by tcomb-validation) and I'd like to just pass it into the form. is this possible?

gcanti commented 8 years ago

Using the hasError, error options? Something like:

const Type = t.struct({
  name: t.String,
  age: t.Number
});

const result = t.validate({}, Type); // fake server validation

function getOptionsFromValidationResult(Type, result) {
  const options = {
    fields: {}
  };
  result.errors.forEach((error) => {
    options.fields[error.path[0]] = {
      hasError: true,
      error: error.message
    };
  });
  return options;
}

const options = getOptionsFromValidationResult(Type, result);

const App = React.createClass({

  getInitialState() {
    return {options, value: {}};
  },

  onSubmit(evt) {
    evt.preventDefault();
    var value = this.refs.form.getValue();
    if (value) {
      console.log(value);
    }
  },

  onChange(value) {
    // reset server error messages
    if (this.state.options === options) {
      this.setState({options: {}, value});
    }
  },

  render() {
    return (
      <form onSubmit={this.onSubmit}>
        <t.form.Form
          ref="form"
          type={Type}
          options={this.state.options}
          value={this.state.value}
          onChange={this.onChange}
        />
        <div className="form-group">
          <button type="submit" className="btn btn-primary">Save</button>
        </div>
      </form>
    );
  }

});