Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

easy-form

Package Overview
Dependencies
Maintainers
1
Versions
16
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

easy-form

A React HOC for validating form easily

  • 1.8.0
  • latest
  • npm
  • Socket score

Version published
Weekly downloads
0
decreased by-100%
Maintainers
1
Weekly downloads
 
Created
Source

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.

Keywords

FAQs

Package last updated on 05 Apr 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc