Skip to content

Validation

Artem Kuzko edited this page Mar 18, 2017 · 1 revision

Validation Rules

react-form-base's Form gives you a mechanism to define any validation of your choice that can be applied to input values as user changes them. First step is to define Validation Rules. If you have a base form in your application with a shared functionality, you should define static validations property there:

import Form from 'react-form-base';

// you can use third-party validation in rules:
import isEmail from 'validator/lib/isEmail';

class BaseForm extends Form {
  static validations = {
    presence: function(value) {
      if (!value) return 'cannot be blank';
    },
    email: function(value) {
      if (value && !isEmail(value)) return 'should be an email';
    },
    numericality: function(value, options) {
      const { greaterThan } = options;
      const fValue = parseFloat(value);

      if (isNaN(fValue)) return 'should be a number';
      if (greaterThan != undefined && fValue <= greaterThan) {
        return `should be greater than ${greaterThan}`;
      }
    }
  };
}

Form Validation With Defined Rules

After you have defined static validation rules you can use them in your application forms:

import BaseForm from 'base-form';

class UserForm extends BaseForm {
  validations = {
    email: ['presence', 'email'],
    fullName: 'presence',
    age: { presence: true, numericality: { greaterThan: 18 } }
  };

  render() {
    return (
      <div>
        <TextField {...this.$('firstName')} />
        <TextField {...this.$('email')} />
        <TextField {...this.$('age')} />

        <button onClick={this.performValidation.bind(this)}>Validate</button>
      </div>
    );
  }
}
Clone this wiki locally