gcanti / tcomb-form

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

Help with validation #223

Closed mvlach closed 8 years ago

mvlach commented 8 years ago

Hi,

I would like to use this awesome library for the registration form. I would like to validate two password fields what have the same value. How can I accomplish this ? I would like to use the validation mechanism, not manually check values in the submit method...

Thanks Mila

gcanti commented 8 years ago

Hi, the simplest way is to define a refinement:

function samePasswords(x) {
  return x.newPassword === x.confirmPassword;
}

const Type = t.refinement(t.struct({
  newPassword: t.String,
  confirmPassword: t.String
}), samePasswords);

const options = {
  error: 'Passwords must match',
  fields: {
    newPassword: { type: 'password' },
    confirmPassword: { type: 'password' }
  }
};

var App = React.createClass({

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

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

});
mvlach commented 8 years ago

super, thanks :)

mvlach commented 8 years ago

Hi,

I would like to study this library but I have no idea where to start. I can make simple form and simple validation. But I can't create complex form with complex validation rules. You mentioned the refinement but I can't find any documentation about it.

I have experience from Java validation JSR 303, but I don't understand the basics....

I would like to have a complex form with name, surname, email, password, confirmPassword. Here is in refinement structure with two fields and this is passed to the <Form ...>

The questions are:

  1. how to describe more field with another validation rules (email)
  2. how to render error message for the confirmPassword field only (the samePasswords).
  3. is there any fully customized form (with the templates)

I know this issue is more complex but I please for another help.

thanks Mila