1.8.0 • Published 5 years ago

easy-form v1.8.0

Weekly downloads
1
License
MIT
Repository
-
Last release
5 years ago

Easy Form

Easy Form is a React HOC that allow you to build forms easily and flexibly.

Example

Demo

Material-UI

Features

  • easy: manage form state conveniently
  • flexible: create awesome form easily with Material-UI, Ant-Design, Redux or any library you like.
  • powerful: support sync/async validation both.
  • tiny: only 19.7kb ungzipped.

Get Started

  1. Run yarn add easy-form react react-dom prop-types

  2. Render it!

import React from 'react';
import { ValidationField, createForm } from '../src';

const schema = {
  name: {
    validator: name =>
      new Promise((res, rej) => {
        setTimeout(() => {
          if (name) {
            res(name);
          } else {
            rej(name);
          }
        }, 200);
      }),
    message: 'Please input your username',
  },
  password: {
    validator: password => password,
    message: 'Please input your password',
  },
};

class LoginForm extends React.PureComponent {
  handleSubmit = e => {
    e.preventDefault();
    const { submit } = this.props;
    submit(data => console.log(data), error => console.log(error))();
  };
  render() {
    const { isValid } = this.props;
    return (
      <form onSubmit={this.handleSubmit}>
        <ValidationField name="name" label="Username">
          <input placeholder="Username" />
        </ValidationField>
        <ValidationField name="password" label="Password">
          <input placeholder="Password" />
        </ValidationField>
        <button
          style={{
            display: 'inline-block',
            marginLeft: 180,
          }}
          disabled={!isValid}
          type="submit">
          Login
        </button>
      </form>
    );
  }
}

export default createForm({}, schema)(LoginForm);

Apis

createForm(defaultValues, schema, options)

usage:

const schema = {
  birth: {
    validator: date => (date ? true : false),
    message: 'Please input your date of birth',
  },
  description: [
    {
      validator: description => (description ? true : false),
      message: 'Please input your description',
    },
    {
      validator(date) {
        return new Promise((res, rej) => {
          setTimeout(() => {
            date === 'loading' ? res(date) : rej(date);
          }, 0);
        });
      },
      message: name => `"${name}" is not my name!`,
    },
  ],
};
const DecoratedForm = createForm(
  {
    birth: '2018-05-28',
  },
  schema,
  { fieldRender },
)(CustomizedForm);

defaultValues: Object

Default values of the form.

schema: Object<[field: string]: Validator>

validator: (target: any, values: Object, preValues: Object, customOptions: Object) => bool | Promise

The validation rules of the form. You pass an array to customize more than one validators. And the validators will be executed sequentially. If validation passes, it should return true or a resolved promise. Else, it should return false or a rejected promise. The message should be a string or a function that receives value of input and result of validation and returns a string.

options: Object

PropertyTypeDefault valueDescription
fieldRenderFuncfieldRenderThe field render prop. Arguments: fieldProps: Object - Props collection of form field Returns Object — The React node to render.
onFormChangeFuncCallback fired when the value of ValidationField gets changed. Arguments: props: Object — Props of The form component changedValue: Object — Value of the changed field defaultHandler: Func - Default handler
onFormResetFuncCallback fired when the form is reset. Arguments: props: Object — Props of The form component newValues: Object — The reset value defaultHandler: Func - Default handler
getValueFromEventFuncCustomized method to get value from event arguments. Arguments: same as event callback

If the form has been decorated by createForm then it owns APIs as follows:

PropertyTypeDescription
isValidboolWhether the form is valid (has no validation error).
isPristineboolWhether the current values of form are different from the initial values.
isValidatingboolWhether the form is validating.
initializeFuncResets the form to specified values.
submitFuncSubmits the form. Returns a promise that will be resolved when the form is submitted successfully, or rejected if the submission fails. Arguments: onSuccess: Func onFail: Func
updateValuesFuncUpdates values of the form. Arguments: newValues: Object
updateSchemaFuncUpdates schema of the form. Arguments: newSchema: Object
validateAllFuncValidates the form.
validateItemFuncValidates the specified field. Arguments: name: string - Name of the field to validate

ValidationField

PropertyTypeDefault valueDescription
formatterFuncThe Handler that format the value. Arguments: value: string \| boolean \| number — The value of input. Returns Object — The formatted value.
namestringRequiredThe unique identifier of field, corresponding to a value in the form values.
onValidateFuncCallback fired after validation. Arguments: result: Object — The result of validation. You can pull out the return of the validator by accessing result.promiseValue.
optionsObjectAdditional options that can be passed to the validator function.
renderFuncRequiredA render prop. Use the property to get what to render. Arguments: props: Object — Please refer to options.fieldRender. Returns Object — The React node to render.
triggerstringonChangeWhen to collect the value of children node.
validateTriggerstringonChangeWhen to validate the value of children node.
valuePropNamestringvalueProp that should be validated. For example, the valuePropName of checkbox is checked.
1.8.0

5 years ago

1.7.1

5 years ago

1.7.0

6 years ago

1.6.0

6 years ago

1.5.0

6 years ago

1.4.0

6 years ago

1.3.1

6 years ago

1.3.0

6 years ago

1.2.2

6 years ago

1.2.0

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago

0.2.0

6 years ago

0.1.1

6 years ago

0.0.2

6 years ago

0.0.1

6 years ago