react-formality

1.4.23 • Public • Published

React formality

A thin wrapper around forms and field components to easily allow validation and debugging in ReactJS.

What does it do?

It simplifies the handeling of validation through thinly wrapping your components in our Form and Field components. This library makes no assumptions about your layout or design, instead it exposes the values and the validation results of the fields through onSubmit, and allows you to retain control all along the way - it doesn't even mutate your component's state, thus allowing you to control when your component redraws or it state mutates.

How does it do it?

Integration hooks

The library allows you to integrate with the inner workings via a few integration hooks, here they are:

  • error prop - if there is a validation error, this prop will be passed to your component, and will be true
  • helperText prop - if there is a validation error, this prop will be passed to your component, and will contain the error message as passed in from validate.js
  • debug prop - if you set this prop on the Field component, we will log information about the events and lifecycle of the component, such as: getValue, validateField, handleChange, handleBlur, fieldCreated. Each will have information specific to the event or lifecycle.
  • onSubmit - the Form component has a special onSubmit event that you can subscribe to - it still receives the oriignal event, but also the form values, form validation result and the form validation result object, so that all you need to do is persist your data.

Note: All lifecycle integration hooks pass on their event, so that you can react on it separately if you wish. Eg: the onChange will still be called in your component, even though we're handling that event.

Built in validation

The built in validation uses validate.js to allow each component to be validated - it has a bunch of built in validators, however you can also define custom validations if you need them.

A few things to note:

  • Validation is initially run onChange, and subsequently each time the component renders, which follows the same pattern as most other validation libraries
  • We do not support async validation, if you need that please log a ticket.
  • onSubmit will trigger validation of all fields in the form that has

Examples

With a custom component

Say you have a custom input field component - the only requirement is that you handle the error and helperText props:

class InputComponent extends Component {
    render(){
        // We extract the error and helperText props, so that the input doesn't receive them
        const { error, helperText, ...rest } = this.props;
 
        return <div>
            <input type="text"{...rest} />
            {/* Display validation error if it exists */}
            {error &&
                <div>
                    <hr aria-hidden="true" style={{borderBottom: "1px solid red"}}/>
                    <div style={{color: "red"}}>{helperText}</div>
                </div>
            }
        </div>
    }
};

With material-ui

Say you're using http://www.material-ui.com, and want to validate your email field before saving the values, you can simply do the following:

import React, { Component } from 'react';
import { TextField } from '@material-ui/core';
import { Field, Form, Store } from 'react-formality'
 
// Setup our validations (you can also place it inline of the field), see https://validatejs.org/ for included validation methods
var validations = {
    emailAddress: {
        presence: true,
        email: true
    }
};
 
class MyApp extends Component {
    // Use this to handle submitting of the data - it is passed the synthetic 
    // event, values from the store, isValid, and the validation results.
    handleSubmit(e, values, isValid, validationResults){
        e.preventDefault();
        if(isValid) {
            console.log('Valid, so we can save here', values);
        } else {
            console.log('Invalid, so we won\'t save', values, validationResults);
        }
    }
 
    componentWillMount() {
        var me = this;
        this.setState({
            // Create a store - you can optionally set values - they ae keyed by the name of the field
            store: new Store({
                emailAddress: "test@example.com"
            },
            // This is called when the store values change - we don't mutate your state, so you must manually force an update
            function(){
                me.forceUpdate();
            })
        });
    }
 
    render() {
        return (
            <div className="route route__signup">
                <h1>Form test</h1>
 
                <Form onSubmit={this.handleSubmit.bind(this)} debug={true}>
                    <div>
                        {/* 
                            Basic email field with validation
                            The value will be stored in the store as 'emailAddress'
                        */}
                        <Field
                        name="emailAddress"
                        store={this.state.store}
                        placeholder="Email address"
                        component={TextField}
                        validate={validations.emailAddress}/>
                    </div>
                </Form>
 
            </div>
        );
    }
}
 
export default MyApp;

So that will validate the email before submitting.

Dependencies (4)

Dev Dependencies (28)

Package Sidebar

Install

npm i react-formality

Weekly Downloads

1

Version

1.4.23

License

MIT

Unpacked Size

223 kB

Total Files

43

Last publish

Collaborators

  • jsguy