All Projects → Bynder → react-formulation

Bynder / react-formulation

Licence: MIT license
Simple React form validation

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to react-formulation

Rich Model Forms Bundle
Provides additional data mappers that ease the use of the Symfony Form component with rich models.
Stars: ✭ 198 (+1314.29%)
Mutual labels:  forms, form
Vue Form Json Schema
Create forms using JSON schema. Bring your components!
Stars: ✭ 253 (+1707.14%)
Mutual labels:  forms, form
Form bloc
🔥 Dart and Flutter Package 🔥 Easy Form State Management using BLoC pattern 🔥 Wizard/stepper forms, asynchronous validation, dynamic and conditional fields, submission progress, serialization and more! 🔥
Stars: ✭ 239 (+1607.14%)
Mutual labels:  forms, form
React Redux Form
Create forms easily in React with Redux.
Stars: ✭ 2,099 (+14892.86%)
Mutual labels:  forms, form
ember-validity-modifier
Ember Octane addon to add custom validity (form validation) to form fields
Stars: ✭ 28 (+100%)
Mutual labels:  forms, form
React Form
⚛️ Hooks for managing form state and validation in React
Stars: ✭ 2,270 (+16114.29%)
Mutual labels:  forms, form
Final Form
🏁 Framework agnostic, high performance, subscription-based form state management
Stars: ✭ 2,787 (+19807.14%)
Mutual labels:  forms, form
Core
The Form Tools Core.
Stars: ✭ 156 (+1014.29%)
Mutual labels:  forms, form
svelte-multistep-form
Svelte MultiStep Form like, this component is still in beta stage
Stars: ✭ 29 (+107.14%)
Mutual labels:  forms, form
FrontendForms
A module for ProcessWire CMS to create and validate forms on the frontend easily using the Valitron library.
Stars: ✭ 0 (-100%)
Mutual labels:  forms, form
Composable Form
Build type-safe composable forms in Elm
Stars: ✭ 179 (+1178.57%)
Mutual labels:  forms, form
final-form-arrays
Array Mutators for 🏁 Final Form
Stars: ✭ 64 (+357.14%)
Mutual labels:  forms, form
React Apollo Form
Build React forms based on GraphQL APIs.
Stars: ✭ 178 (+1171.43%)
Mutual labels:  forms, form
Redux Form
A Higher Order Component using react-redux to keep form state in a Redux store
Stars: ✭ 12,597 (+89878.57%)
Mutual labels:  forms, form
Fielder
A field-first form library for React and React Native
Stars: ✭ 160 (+1042.86%)
Mutual labels:  forms, form
Fui
Add CLI & form interface to your program. Docs: https://docs.rs/fui
Stars: ✭ 244 (+1642.86%)
Mutual labels:  forms, form
Forms
📝 Simple form & survey app for Nextcloud
Stars: ✭ 127 (+807.14%)
Mutual labels:  forms, form
Reactive forms
This is a model-driven approach to handling form inputs and validations, heavily inspired in Angular's Reactive Forms
Stars: ✭ 135 (+864.29%)
Mutual labels:  forms, form
react-apollo-form
Build React forms based on GraphQL APIs.
Stars: ✭ 195 (+1292.86%)
Mutual labels:  forms, form
talos
Elixir parameter validation library. Simple and extensible
Stars: ✭ 23 (+64.29%)
Mutual labels:  forms, validate

React Formulation

Easy form validation

Inspired by react-reformed

Table of Contents

  1. Installation
  2. Demo
  3. Usage
  4. HOC
  5. Inline Form
  6. Advanced
  7. Custom validation rules
  8. Custom error messages
  9. API
  10. Component options

Installation

npm install @bynder/react-formulation --save

Demo

If you want to try out a little demo first, you can check it out here or try it yourself:

git clone [email protected]:Bynder/react-formulation.git
cd react-formulation
npm install
npm start

Usage

React formulation offers two types of forms. The first one is a high order component for larger forms, the second one is a component for a form with just one input field and a submit and cancel button.

HOC

If you have a larger form you'll use the High order component:

import { withValidation, Validator } from '@bynder/react-formulation';

@withValidation({
    validateOn: 'change', // optional, default value is 'blur'
    schema: {
        firstname: {
            required: true,
        },
        lastname: {
            minLength: 2,
            maxLength: 30,
        },
        // ...more validation rules
    }
})
class YourForm extends React.Component {
    componentWillMount() {
        this.props.setInitialModel({
        	firstname: 'Foo',
        	lastname: 'Bar',
        });
    }

    onSubmit() {
        // handle submit
    }

    render() {
        // Wrap your entire form in a <Validator.Form> component
        // Add a submit handler
        // Wrap every input in a <Validator> component
        // Provide a name to Validator (must match the name you provided in the schema)
        return (
            <Validator.Form onSubmit={this.onSubmit}>
                <Validator name="firstname">
                    <input />
                </Validator>
                <Validator name="lastname">
                    <input />
                </Validator>
                <button type="submit">Submit</submit>
            </Validator.Form>
        );
    }
}

export default YourForm;

Inline Form

For forms with just a single input you'll use the Inline Form component

import { InlineForm } from '@bynder/react-formulation';

// Wrap your input and buttons in an <InlineForm> component.
// Provide the name of your input, validation rules, initial value,
// and optionally custom messages to this component.
// Add an onSubmit handler.
// Wrap the input in a <InlineForm.Field> component.
const YourInlineForm = () => (
    <InlineForm
        name="firstname"
        initialValue="Foo"
        rules={{
            required: true,
            minLength: 2,
            maxLength: 30,
        }}
        messages={{
            // Custom validation messages
            required: 'Please don\'t leave me empty',
            minLength: condition => `Please use a minimum of ${condition} characters`,
        }}
        onSubmit={(val) => { // handle submit }}
    >
        <InlineForm.Field resetOnEscape>
            <label htmlFor="inlineform-name">Name</label>
            <input id="inlineform-name" />
        </InlineForm.Field>
        <InlineForm.Errors /> // (optional) This will display the error messages
        <InlineForm.Cancel> // (optional) This will reset your form when you click cancel
            <button type="button">
                Cancel
            </button>
        </InlineForm.Cancel>
        <InlineForm.Submit> // (optional) This disables the submit button if the field isn't valid
            <button type="submit">
                Save
            </button>
        </InlineForm.Submit>
);

export default YourInlineForm;

Advanced

The basic usage might not be enough for you. Luckily we added some advanced options.

Custom validation rules

Of course you can add your own validation rules to the schema. Here you can see an example of how that might work:

@withValidation({
    schema: {
        name: {
            required: true, // default validation
            mustNotContainSpecialCharacters: { // custom validation
                test: val => !(/[^a-zA-Z0-9]/).test(val),
                message: 'This field cannot contain special characters',
            },
        },
        // ...
    }
})
// ...

Custom error messages

In the example above you can see that it's possible to add custom validation rules and custom messages for those rules. You can also add custom messages for the default validation rules. You can use this option to add translations.

@withValidation({
    schema: {
        name: {
            required: true,
        },
        // ...
    },
    messages: {
        required: 'This field is required.',
    }
})
// ...

API

The following options are injected by the react-formulation high order component.

setInitialModel(model: Object)

Allows you to set the initial values of the model

Usage:

this.props.setInitialModel({
    firstname: 'Foo',
    lastname: 'Bar',
});

isTouched: boolean

Returns true if any of the fields have been changed, otherwise returns false.

Usage:

this.props.isTouched;

getSchema(name: String)

Returns the errors for the given input (name).

Usage:

this.props.getSchema('lastname');

Returns:

// console.log(this.props.getSchema('lastname'));
{
    errors: [{
        condition: true,
        rule: 'required'
    }],
    isTouched: true,
    isValid: false,
}

schema: Object

Returns the complete error schema.

Usage:

<button disabled={!this.props.schema.isValid && !this.props.isTouched} />

Returns:

// console.log(this.props.schema);
{
    isValid: true,
    fields: {
        firstname: {
            errors: [],
            isTouched: true,
            isValid: true
        },
        lastname: {
            errors: [{
                condition: true,
                rule: 'required'
            }],
            isTouched: true,
            isValid: false,
        }
    }
}

validateForm(initialModel: Object [optional])

Validates the entire form.

Usage:

this.props.validateForm();

setProperty(prop: String, value: Any)

Set a specific property on a model.

Usage:

this.props.setProperty('firstname', 'foo');

setModel(model: Object)

Override the existing model

Usage:

this.props.setModel({
    firstname: 'bar',
    lastname: 'foo',
});

isButtonDisabled: boolean

Tells you if your submit button should be disabled.

Usage:

<button type="submit" disabled={this.props.isButtonDisabled} />

resetValidation(): Function

Removes the validation errors from your form, sets isValid to null.

Usage:

this.props.resetValidation();

Returns:

// console.log(this.props.schema);
{
    isValid: null,
    fields: {
        firstname: {
            errors: [],
            isTouched: false,
            isValid: null
        },
        // ...
    }
}

clearForm(): Function

Removes all values from all models.

Usage:

this.props.clearForm();

resetForm(): Function

Resets the validation and sets the form to its initial model.

Usage:

this.props.resetForm();

setTouched(): Function

Sets the forms touched state to true.

Usage:

this.props.setTouched();

setUntouched(): Function

Sets the forms touched state to false.

Usage:

this.props.setUntouched();

model: Object

Returns the complete model.

Usage:

this.props.model;

Returns

{
    firstname: {
        isTouched: false,
        value: 'Foo'
    },
    lastname: {
        isTouched: true,
        value: 'Bar'
    },
    phone: {
        isTouched: false,
        value: '0123456789'
    }
}

Component options

<Validator />

Property Type Default Description
name string undefined Name of the model
hideErrors bool false Hide error messages

<Validator.Form />

Property Type Default Description
onSubmit func undefined Submit handler
... props

<InlineForm />

Property Type Default Description
name string undefined Name of the model
initialValue object undefined Initial value of the model
onSubmit func undefined Submit handler
rules object undefined Validation rules
messages object undefined Custom validation messages
... props

<InlineForm.Field />

Property Type Default Description
resetOnEscape bool false Resets the input value on escape
... props

<InlineForm.Errors />

Property Type Default Description
... props

<InlineForm.Cancel />

Property Type Default Description
style object { display: 'inline' } CSS style attribute
... props

<InlineForm.Submit />

Property Type Default Description
style object { display: 'inline' } CSS style attribute
... props
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].