npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

generic-form

v1.2.2

Published

![logo](https://s3.amazonaws.com/word-art/5c5c51c120152c19834ad3d2.png)

Downloads

977

Readme

GenericForm npm

logo

GenericForm is a React form validation plugin. Each form field can use a validation prop to define what format is expected.

Installation

$ yarn add generic-form

Components

The library uses a form ID to handle form validation. You may use the GenericForm component with a fields prop to create your form or you can use standard JSX and inject GenericFormField components into the form by specifying the formId prop.

Examples

A GenericForm component that handles its own fields

<GenericForm
  id="my-form"
  fields={[
    {
      type: GenericFormFieldType.EMAIL,
      id: "my-form-email",
      name: "email",
      validation: {
        mandatory: true,
      },
    },
    {
      type: GenericFormFieldType.PASSWORD,
      id: "my-form-password",
      name: "password",
      validation: {
        mandatory: true,
      },
    },
    {
      type: GenericFormFieldType.SUBMIT,
      value: "Login",
    },
  ]}
/>

A GenericForm that uses GenericFormField components

<GenericForm id="my-form">
  <GenericFormField
    formId="my-form"
    type={GenericFormFieldType.EMAIL}
    name="email"
    id="my-form-email"
    validation={{ mandatory: true }}
  />
  <GenericFormField
    formId="my-form"
    type={GenericFormFieldType.PASSWORD}
    name="password"
    id="my-form-password"
    validation={{ mandatory: true }}
  />
  <GenericFormField
    formId="my-form"
    type={GenericFormFieldType.SUBMIT}
    value="Login"
  />
</GenericForm>

Validation

Validation Object

mandatory (boolean)

marks the field as mandatory, if value isn't set by user it will display the 'errorEmpty' string

validateOnBlur (boolean, default: true)

by default, genericForm validate each field on Blur event

errorEmpty (string)

The string will be displayed if the field is empty and the mandatory boolean was set

customErrorHandlers (object)

The customErrorHandlers prop allows you to define functions that will check the field's value and return the key you defined as an error if the check is truthy

<GenericFormField
    validation={ {
        customErrorHandlers: {
            'Do not enter "Bad value"':  v => v === 'Bad value'
        }
    } } />

positiveRegex (object)

The positiveRegex prop allows you to define props that will trigger errors when the value of the field matches the regex.

<GenericFormField
    validation={ {
        positiveRegex: {
        'No commas are allowed': /,/
        }
    } } />

negativeRegex (object)

The negativeRegex prop allows you to define props that will trigger errors when the value of the field doesn't match the regex.

<GenericFormField
    validation={ {
        negativeRegex: {
        'The field must contain a comma': /,/
        }
    } } />

group (string)

The group prop marks a field as part of a group, at least one (or groupMin) fields in a group should be valid for the form to be validated, if the requirement isn't met the field will display the errorGroup prop

<GenericFormField
    validation={ {
        group: 'field-group',
        groupMin: 1,
        errorGroup: 'At least one of these fields is required'
    } } />

identicalGroup (string)

The identicalGroup prop marks a field as part of a group where all values must be equal. If the requirement isn't met the field will display the errorIdenticalGroup prop.

<GenericFormField
    validation={ {
        identicalGroup: 'field-group',
        errorIdenticalGroup: 'These fields must be identical'
    } } />

disableUntilValid

This prop disables a field until all fields in the form are valid:

<GenericFormField
    formId="test"
    type="submit"
    disableUntilValid />

Other props

maxLength (number)

This crops the fields value to a given length (even for non number types)

defaultEmptyValue (any)

GenericFormField is always controlled by default if no value or defaultValue is set we use an empty string, however you may override this behaviour with the defaultEmptyValue prop

requiredLabelSuffix (string)

Add a string to the label (can be usefull for accessibility and/or to show that an input is required)

outputEmptyFields(boolean)

If set to true, empty fields will be appended to form data output

Using external libraries

The package supports external library components through the GenericFormField static method 'registerExtraType'.

registerExtraType arguments

type (string)

A string to identify the new GenericFormField type

customComponent methods (object)

An object that has two methods, render and getValue:

render(libraryProps, componentProps, libraryState, validateOnChange)

The render method should return the custom component. The validateOnChange method can be called to customize the component onChange callback.

getValue

A method scoped to the component that allows access to component props and should return the component value.

registerExtraType example

Here is an example of how to register a custom component into the form validation using the react-text-mask plugin.

GenericFormField.registerExtraType('mask', {
  render(sharedProps, { mask, onChange }, state, validateOnChange) {

    return <TextMask
      { ...sharedProps }
      mask={ mask }
      guide={ false }
      onChange={(e) => {
        // by default sharedProps pass in onChange method that does validation, but this can be overriden while keeping validation by using the validateOnChange method
        validateOnChange(e);
        if (typeof onChange === 'function') onChange(e);
      }}
      type='text'/>;

  },
  getValue() {
    return this.el.current.inputElement.value;
  },
});

By registering an extra type you may then use the component in your forms by simply using the string you registered:

<GenericFormField
    id='masked-field'
    name='masked-field'
    type='mask'
    mask={[/\d/, /\d/, /\d/, /\d/,'-', /\d/, /\d/]} />

setRequiredLabelSuffix

This method allows you to set a global suffix for required labels

GenericFormField.setRequiredLabelSuffix('*');

You can override this value for any input by using the requiredLabelSuffix props

Using custom Field component with GenericForm

You can give the GenericForm a FieldComponent prop that will be used when giving the GenericForm an array of fields

Changing default error message

import {setErrors } from 'generic-form';

setErrors({ mandatory: 'My error' });

Scripts

Running the example form

An example is provided with the repository, you may start the parcel dev server by running the following command:

$ yarn example

Building the module

$ yarn build