gcanti / tcomb-form

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

Form validation autofocus? #175

Closed MartynasZilinskas closed 9 years ago

MartynasZilinskas commented 9 years ago

How to make autofocus first failed field in form?

Thanks for answers in advance.

gcanti commented 9 years ago

Hi, I'd use the validate (https://github.com/gcanti/tcomb-form/blob/master/GUIDE.md#validate) and getComponent API (https://github.com/gcanti/tcomb-form/blob/master/GUIDE.md#how-to-get-access-to-a-field):

Example

import React from 'react';
import t from 'tcomb-form';

var Type = t.struct({
  name: t.Str,
  surname: t.Str
});

const App = React.createClass({

  onSubmit(evt) {
    evt.preventDefault();
    // validate() return the raw validation result (see tcomb-validation for details)
    var validationResult = this.refs.form.validate();
    if (validationResult.isValid()) {
      // form is ok
      console.log(value);
    }
    else {
      // form is KO, let's focus the first invalid field
      var component = this.refs.form.getComponent(validationResult.errors[0].path);
      var formGroupElement = React.findDOMNode(component);
      formGroupElement.children[1].focus();
    }
  },

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

});