0.7.2 • Published 4 months ago

form-ctrl-vanilla v0.7.2

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

FORM-CTRL-VANILLA

Zero dependency vanilla js form control map for multiple forms with values, state, validation. FormCtrl class can be extended for custom usage.

Install

npm install form-ctrl-vanilla

Usage

import formCtrl from 'form-ctrl-vanilla';

const form = formCtrl.create('form_id_1', { validationEventName: 'onChange' });

const form2 = formCtrl('form_id_2'); // get or create
form2.options = { validationEventName: 'onChange' };

form.setValues({ field_1: 5, field_2: 'asd' });

form.handleChange('field_1', changeEvent); // changeEvent.target.value will be used
form.handleBlur('field_1');

form.setFieldValidation('field_1', {
  eventName: 'onChange',
  required: 'Required field',
  rules: [
    {
      message: 'Must be more than 10',
      type: 'error',
      typeIfPassed: 'success',
      validate: (value) => value > 10,
      eventName: 'onBlur',
    },
  ],
});

const {
  touched, // count number, changed by user
  changed, // count number
  blurred, // count number
  messages, // [{ message: 'Must be more than 10', type: 'error' }]
  error, // boolean
  warning, // boolean
} = form.getFieldState('field_1');

if (form.touched) { /*...*/ }
if (form.changed) { /*...*/ }
if (form.hasErrors) { /*...*/ }
if (form.hasWarnings) { /*...*/ }

form.clear();

form.reset({ field_1: 4 });

form.destroy();

Extend

Implementation for React

import { FormCtrl as FormCtrlVanilla } from 'form-ctrl-vanilla/FormCtrl';

class FormCtrlCustom extends FormCtrlVanilla {
  constructor(options) {
    super(options);
  }

  // this method is used in base class when rerender should happen
  // for example after field value changes
  // or validation results in changed messages
  rerenderFields(fields) {
    // trigger rerender
  }

  getCustomFieldState(field) {
    return this.getFieldState(field).customState;
  }
}
0.7.2

4 months ago

0.7.1

4 months ago

0.7.0

4 months ago

0.6.1

5 months ago

0.6.0

5 months ago

0.5.1

5 months ago

0.5.0

5 months ago