1.0.11 • Published 5 years ago

mp-form-validator v1.0.11

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

mp-form-validator

It's just a simple form validator with hooks, custom rules, translations, overriding functions.

Bundle size: 7,57KB

In Development

Installation

npm i mp-form-validator

Usage

import Validator from "mp-form-validator"

or

import "mp-form-validator/bundle/validator.bundle.min.js"

or

<script src="//unpkg.com/mp-form-validator@1.0.11/bundle/validator.bundle.min.js"></script>

Next, create new Validator instance:

var v = new Validator({...params});

Params object:

propertyvalue typedesc
debugbooleanShow/hide debug messages in console
errorWrapperClassstringClass name for errors wrapper
errorClassstringClass name of single error
errorPositionstring ('before' or 'after')Where place a error - before or after input
languagestringLang code, if not found load default english.
constraintsobjectObject of constraints
translationsobjectObject of translations. Passed override language passed above.

Default params object:

var paramas = {
    debug: false,
    errorWrapperClass: 'form-errors-msgs',
    errorClass: 'single-error-msg',
    errorPosition: 'before',
    language: 'en',
    constraints: {},
    translations: {}
}

Methods

methodparamreturndesc
validateFieldfield,forceValuebooleanvalidate single field
validateFormformbooleanvalidate passed form
isFormValid-booleancheck if form is valid
removeAllErrorMessages-voidremove all added messages to form elements
getErrors-objectget all form errors

...where:

  • field - DOM element
  • form - DOM element
  • forceValue - string/boolean - sometimes value of your field is changing with delay (e.g. react setState() method, field is binded with state value, but metod works async and value of DOM element will be one change before - NOW you can pass directly field value and all works fine :))

Constraints

By default, Validator don't know, what you want to validate - so, let's go!

Sample definition of constraints:

var constraints = {
    firstName: {
        required: true,
    },
    phone: {
        required: true,
        phone: true
    },
    email: {
        required: true,
        email: true
    }
};

var params = {
    ...params,
    constraints: constraints
}

firstName, phone, email are just name of form elements. Each form element must have a unique name.

Order of processing rules is just order of rules in your Constraint object - for field with name phone first will be 'required', second 'phone'.

...and rules

For now, we have only 8 rules available - yes - it's simple but powerful validator :>

ruleNamedescription
requiredcheck if length of field > 0; if checkbox or radio, check if input group has any checked values
phonecheck if have only digits and 9 numbers
emailsimple check email
passwordcheck if password has 1 lower, 1 upper, 1 numeric, 1 special and >= 8 chars
peselcheck for polish pesel number
regoncheck for polish regon number
nipcheck for polish nip number
idCardcheck for polish idCard number

Custom rules

Yes - you can define your own logic for rules.

For example - you want to validate if entered text >= 10 characters.

First, define your rule:

var rules = {
    'text-length': {
        valid: function(value, field) {
          return value.length >= 10;
        }
    }
}

...and define translation (if invalid):

var translations = {
    Rules: {
        Errors: {
            'text-length': 'You should enter min. 10 chars or greater'
        }
    }
}

...and pass it to your params:

var params = {
    ...params,
    rules: rules,
    translations: translations
}

Translations

Create own translations object that should be like example below:

var translations = {
    Rules: {
        Errors: {
            "required": "This field is required.",
            "phone": "Incorrect phone format. Should be exact 9 digits.",
            "email": "Incorrect email address.",
        }
    }
}

and pass your object to params:

var params = {
    ...params,
    translations: translations
}

Hooks

Plugin have some hooks inside. You can override default hook, by passing to params object, a function definition:

functionNameparams
onFieldValidateErrorfield,value,errorMessages
onFieldValidateSuccessfulfield, value
onFormValidationErrorform, errorMessages
onFormValidationSuccessfulform
beforeFieldValidationfield
afterFieldValidationfield
beforeFormValidationform
afterFormValidationform

...where:

  • field - DOM element
  • form - DOM element
  • value - string/boolean with field value
  • errorMessages - object with errors, where key is a field name, ale value is an array of validation messages

Sample usage:

var params = {
    ...params,
    onFormValidationError: function(form, errorMessages) {
      form.querySelector('.btn-submit').classList.add('disabled')
    },
    onFormValidationSuccessful: function(form) {
      form.querySelector('.btn-submit').classList.remove('disabled')
    }
}

Notice:

  • There's no auto-validation on submit, you have full control over when & how. More in index.html

Sorry for everything - it's my first package, if you found a bug, report - thanks!

License

ISC

1.0.11

5 years ago

1.0.10

5 years ago

1.0.9

5 years ago

1.0.8

5 years ago

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago