1.1.0 • Published 5 years ago

@jeremn/form-control-js v1.1.0

Weekly downloads
-
License
ISC
Repository
github
Last release
5 years ago

Install and Tests

Form Validation with Javascript (es6+)

Install

npm i @jeremn/form-control-js
import formControl from '@jeremn/form-control-js'

Usage

formControl take three arguments:

  • forms: an array containing all yours forms object, set to null by default (see Forms).
const forms = [
  {
    form: '.js__form__control--1',
    validate: '',
    fields: [
      {
        field: '#name',
        errorsMsg: {
          isRequired: 'my cutom error message',
          minLen: 'my cutom error message',
          maxLen: 'my cutom error message',
        },
        isRequired: true,
        minLen: 4,
        maxLen: 12,
      }, {
        field: '#number',
        isRequired: true,
      }, {
        field: '#phone',
        isPhone: true,
      }, {
        field: '#email',
        isEmail: true,
      }, {
        field: '#siret',
        isSiret: true,
      }, {
        field: '#bic',
        isBic: true,
      }, {
        field: '#iban',
        isIban: true,
      }, {
        field: '#url',
        isUrl: true,
      }, {
        field: '#checking',
        isChecked: true,
      },
    ]
  }, {
    form: '.js__form__control--2',
    fields: [
      {
        field: '#name2',
        isRequired: true,
        minLen: 4,
        maxLen: 12,
      }, {
        field: '#number2',
        isRequired: true,
      }, {
        field: '#phone2',
        isPhone: true,
      }, {
        field: '#email2',
        isEmail: true,
      }, {
        field: '#siret2',
        isSiret: true,
      }, {
        field: '#bic2',
        isBic: true,
      }, {
        field: '#iban2',
        isIban: true,
      }, {
        field: '#url2',
        isUrl: true,
      }, {
        field: '#checking2',
        isChecked: true,
      },
    ]
  },
]
  • config: an object containing your properties, custom validators, errors messages... that will overwrite the default settings (see Config object).

  • useDateAttr: a boolean, telling formControl to use data-attr or not, set to true by default.

FormControl

  1. Using data-attributes

You can use data-attributes to initialize formControl, see Data-attributes below.

<body>
<form class="form js__form__control--2" data-form-control="true">
    <div class="form__group">
      <label for="name2">Name</label>
      <input 
        id="name2" 
        class="form__field" 
        type="text"
        data-form-validators="isRequired minLen_4 maxLen_12"/>
    </div>
    <div class="form__group form__group--row">
      <button type="submit">Send</button>
    </div>
</form>
</body>

<script>
import formControl from './form-control';

formControl()
</script>
  1. Using forms array

Or you can use forms array to initialize formControl, see Forms below.

<body>
<form class="form js__form__control">
    <div class="form__group">
      <label for="name2">Name</label>
      <input 
        id="name2" 
        class="form__field" 
        type="text"/>
    </div>
    <button type="submit">Send</button>
</form>
</body>
<script>
import formControl from './form-control';

const forms = [ 
  {
    form: '.js__form__control--2',
    fields: [
      {
        field: '#name2',
        isRequired: true,
        minLen: 4,
        maxLen: 12,
      }, {
        field: '#number2',
        isRequired: true,
      }, {
        field: '#phone2',
        isPhone: true,
      }, {
        field: '#email2',
        isEmail: true,
      }, {
        field: '#siret2',
        isSiret: true,
      }, {
        field: '#bic2',
        isBic: true,
      }, {
        field: '#iban2',
        isIban: true,
      }, {
        field: '#url2',
        isUrl: true,
      }, {
        field: '#checking2',
        isChecked: true,
      },
    ]
  },
]

formControl(forms)  
</script>
  1. Adding custom validators

You can add your own validator by:

  • adding an object in customValidators in the config object
const customState = {
  customValidators: {
    myCustomValidator: (value) => { 
      return value != "2"
    }
  }, 
  errorsMsg: {
    isNotEqualTwo: 'Field should not be equal to two'
  }
}

then add the corresponding data-attr:

<input data-form-validators="myCustomValidatorName"/>

or in the field object:

<input data-form-validators="myCustomValidatorName"/>
  • or add in field object your validator
const forms = [
  {
    form: '.js__form-control',
    fields: [
      {
        field: '#text4',
        myCustomValidator: (value) => {
          return value === 'hello'
        },
      },
    ]
  }
]    

in both case, don't forget to add the corresponding error message.

  1. Adding custom error message

You can add custom error message:

  • by setting a data-attr
<input id="text2" class="form__field" type="text" data-error-msg-is-not-equal-two="Field should not be equal to two" />
  • by using the errorsMsg key in config
const customState = {
  ...
  }, 
  errorsMsg: {
    myCustomErrorMsg: 'My error message'
  }
}
  • by using the errorMsg key in field object
const forms = [
  {
    form: '.js__form-control',
    fields: [
      {
        field: '#text4',
        errorMsg: {
          myCustomErrorMsg: 'My error message'
        }  
      }
    ],
  }
]
  1. Changing event type

By default formControl perform validation when the form is submitted, you can use the onFields validation type if you want to perform 'live' validation when a user type in an input field.

To do this, set validationType key in config with the value: onFields

const config = {
  validationType: 'onFields'
}

or use validate key in form object:

const forms = [
  {
    form: '#myFormID',
    validate: 'onFields',
    ...
  }
]

by default input event listener will be used, to change this behavior, you can:

  • add the evtType key in field object
const forms = [
  {
    ...,
    fields: [ 
      {
        field: '.myField',
        evtType: 'keyup'
      }
    ]
  }
]
  1. Adding custom classes

You can set custom CSS classes for field and error text block by passing an object as the config argument (see Config object below for the used properties).

  1. Ajax form

If you need form that send data by ajax you can set callback afterValidation. It will be called only if form is valid and afterValidation is a function. Two arguments will be passed, the current form, and the corresponding fields array.

let validation = formControl(null, {
  afterValidation: (currentForm, fields) {
    '...your code here'
  }
});

Forms

NameTypeDescriptionDefault (if applicable)Example
formStringForm selector (ID, className...)'.jsformcontrol--1'
validateStringValidation type used by FormControl (two possible value: 'onSubmit', 'onFields')'onSubmit''onSubmit'
fieldsArrayFields to validate{ field: '#number', isRequired: true }, {...}

Field object

NameTypeDescriptionExample
fieldStringInput selector (ID, className...)'#name'
validatorsNameBoolean or Value or StringValidator applied to field (see Validators below)minLen: 4
errorsMsgObjectCustom errors messageerrorsMsg: { minLen: 'my custom error msg {{cond}}' }
evtTypeStringEvent applied to field event listener (if validationType = 'onFields')evtType: 'keyup'

Config

NameTypeDescriptionDefault
regexpObjectRegex used by some validatorssee Default regex
errorsMsgObjectErrors message showed when validators return falsesee Default error messages
errorClassStringDefault error class added to containerhas__error
successClassStringDefault success class added to containerhas__success
inputParentClassStringClassName used by input parent container.form__group
inputClassStringClassName used by input field.form__control
fieldMessageClassStringClassName used by field message element.form__message
allowedFileExtensionsArrayAllowed file extension used by validators for inputtype="file"['.jpg', '.jpeg', '.gif', '.png', '.webp']
fieldMessageTemplateTemplate stringError field template used to display error/message message<div class="form__message"></div>
noValidateAttributesArrayThis attributes will not be used by runValidators method['field', 'rule']
noValidateKeysArrayThis keys will not fire the runValidator callback when user use their keyboard['Tab', 'Shift']
validationTypeObjectType of validation used by FormControlonSubmit
fieldEventObjectDefault field event for 'onFields' validation listenerinput
timerObjectDebounce timer for field type validationnull
afterValidationFunctionFunction called after submit validation (if form has no error)null
customValidatorsObjectAn object containing your custom validators functionsnull

Data-attributes

NameDescriptionExample
[data-form-control="true"]Form with this data-attr will be processed by FormControl'<form data-form-control="true">'
[data-form-validators]Apply validation rules on input''
[data-validation-type]Modify validator event listener on form''
[data-event-type]Apply custom event listener on input event listener''
[data-error-msg-my-validator-name]Apply custom error message on input''

Validators

NameDescriptionExample
isRequiredField isn't emptyisRequired
isEmailField is emailisEmail
isSiretField is SiretisSiret
isBicField is BICisBic
isUrlField is SiretisUrl
isIbanField is IBANisIban
isIntegerValue must be integerisInteger
isCheckedField must be checkedisChecked
isPasswordField must be an acceptable password (watch your regex!)isPassword
isEqual_{condition}Field with specified name must have same valueisEqual_#password1
isLen_{condition}Value length equal to conditionisLen_4
isNumericAny valid numberisNumeric
minLen_{condition}Value length must be equal or more then contitionminLen_4
maxLen_{condition}Value length must be equal or less then contitionmaxLen_34
min_{condition}Value must be equal or more then contitionmin_4
max_{condition}Value must be equal or less then contitionmax_34
radioIsCheckedOne radio input must be checkedradioIsChecked
fileHasExtensionFile should have allowed extensionfileHasExtension

Default regex

KeyRegex
isName/\d/
isEmail/^a-zA-Z0-9._+-+@a-z0-9-{1,67}.a-zA-Z{2,67}$/
isPhone/^01-9{1}((0-9{2}){4})((\s0-9{2}){4})((-0-9{2}){4})$/
isIban/^a-zA-Z{2}0-9{2}a-zA-Z0-9{4}0-9{7}(a-zA-Z0-9?){0,16}$/
isBic/(a-zA-Z{4}a-zA-Z{2}a-zA-Z0-9{2}(a-zA-Z0-9{3})?)/
stringRegexp/^\s+<>"\$&\/'*#@\.../
isUrl/^a-zA-Z0-9-.+.(comorgnetmileduCOMORGNETMILEDUfrFritengca)$/
isPassword/^(?=.a-z)(?=.A-Z)(?=.\d)(?=.$@$!%_*?&)A-Za-z\d$@$_!%*?&{6,12}/
msgRegexp/^\s+$/
isNumeric/^0-9+$/
isSiret/^0-9{3} .-?0-9{3} .-?0-9{3} .-?0-9{5}$/

Default error messages

KeyMessage
isEmail'Please enter a valid email adress'
isPhone'Please enter a valid phone number'
isUrl'Please enter a valid url'
isChecked'This field must be checked'
isIban'Your IBAN is invalid'
isSiret'Your Siret is invalid'
isBic'Your BIC is invalid'
isRequired'This field is required'
isNumeric'Value must be set to a number'
isInteger'Value must be an integer'
isEqual'Value must match {{cond}} field'
isLen'Value must contain {{cond}} characters'
isPassword'Password shoud contain 6 to 12 characters, numbers, at least one special character(@$_!%*?&), and at least one uppercase character and one lowercase'
minLen'Value is too short, minimum is {{cond}} characters'
maxLen'Value is too long, maximum is {{cond}} characters'
min'Value is too small, minimum is {{cond}}'
max'Value is too big, maximum is {{cond}}'
quantity'Use digits only'
radioIsChecked'You must checked one field at least'
fileHasExtension'Your file is invalid, this extension is not allowed'
1.1.0

5 years ago

1.0.0

5 years ago

0.0.18

5 years ago

0.0.17

5 years ago

0.0.16

5 years ago

0.0.15

5 years ago

0.0.14

5 years ago

0.0.13

5 years ago

0.0.12

5 years ago

0.0.11

5 years ago

0.0.10

5 years ago

0.0.2

5 years ago