1.0.61 • Published 27 days ago

@chrisjwarnes/form-validator v1.0.61

Weekly downloads
-
License
ISC
Repository
github
Last release
27 days ago

form-validator

replacement for jquery-validate / jquery-validate-unobtrusive, aimed at dot net projects to remove jquery dependency

Node.js CI

Installation (npm)

npm install '@chrisjwarnes/form-validator'

Basic usage

import { initForms, setupValidation } from '@chrisjwarnes/form-validator'

setupValidation()
initForms()

ES6 modules

to use ES6 modules use the following syntax, you will need to do your own transcribing to meet your browser requirements.

import { initForms, setupValidation } from '@chrisjwarnes/form-validator/src' 
setupValidation()
initForms()

Example html for form fields.

All form fields that need to be validated should have the data-val="true" attribute, and at least one other additional attribute to describe the validation type/error message for failure.

Required Field

   <div>
      <label for="name">Name</label>
      <input id="name" name="name" type="text" value="" data-val="true" data-val-required="There are errors in this field">
      <span data-valmsg-for="name" data-valmsg-replace="true"></span>
    </div>

Email (plus required)

 <div>
    <label for="email">Email</label>
    <input type="email" id="email" name="email" data-val="true" data-val-required="This field is required" data-val-email="The email address is invalid">
    <span data-valmsg-for="email" data-valmsg-replace="true"></span>
  </div>

Phone number

  <div>
    <label for="phone">Phone</label>
    <input type="tel" id="phone" name="phone" data-val="true" data-val-phone="this appears to be an invalid phone number">
    <span data-valmsg-for="phone" data-valmsg-replace="true"></span>
  </div>

Regular Expression

   <div>
      <label for="name">Name</label>
      <input id="name" name="name" type="text" value="" data-val="true" data-val-regex-pattern="/^([^0-9]*)$/" data-val-regex="the name field shouldn't contain any numbers">
      <span data-valmsg-for="name" data-valmsg-replace="true"></span>
    </div>

Numeric field

   <div>
      <label for="number">Number</label>
      <input id="number" name="number" type="number" value="" data-val="true" data-val-number="this field should contain numbers only">
      <span data-valmsg-for="number" data-valmsg-replace="true"></span>
    </div>

Maximum length

   <div>
      <label for="name">Name</label>
      <input id="name" name="name" type="text" value="" data-val="true" data-val-regex-pattern="/^([^0-9]*)$/" data-val-max-length-max="50" data-val-max-length="this field shouldn't contain more than 50 characters">
      <span data-valmsg-for="name" data-valmsg-replace="true"></span>
    </div>

Minimum length

   <div>
      <label for="name">Name</label>
      <input id="name" name="name" type="text" value="" data-val="true" data-val-regex-pattern="/^([^0-9]*)$/" data-val-min-length-min="50" data-val-min-length="this field should contain at least 50 characters">
      <span data-valmsg-for="name" data-valmsg-replace="true"></span>
    </div>

Adding additional rules

rules use Async Validation syntax

in order to create a new Rule

import { addRule } from '@chrisjwarnes/form-validator'

The addRule function takes three arguments the first is the attribute for the validation, this is in dataset format i.e. for required validation an attribute of data-val-required will be added to the input therefore the first argument is 'valRequired' as it would appear under the data set property for that input, see Dataset Documentation for more details.

The second argument of addRule is an anonymous function with the argument of a field and returning an object containing the async-validator rule details.

the third argument is an optional boolean field (default: false) which specifys whether or not the rule should only be run on form submission (for example if the rule carrys out ajax requests to the server e.g. recaptcha?) other rules will be fired on blur/input events of the field.

Example rules

  addRule('valMaxlength', function (field) {
    return {
      type: 'string',
      max: parseInt(field.dataset.valMaxlengthMax),
      message: field.dataset.valMaxlength
    }
  })

  addRule('valRecaptcha', function (field) {
    return {
      type: 'string',
      asyncValidator: (rule, value) => {
        return new Promise((resolve, reject) => {
          if (!window.grecaptcha) {
            reject(new Error('grecaptcha script is missing.'))
          }
          window.grecaptcha.execute(field.dataset.valRecaptchaKey, { action: field.dataset.valRecaptchaAction }).then(function (token) {
            field.value = token
            resolve()
          })
        })
      },
      message: field.dataset.valRecaptcha
    }
  }, true)

Async Forms

To make a form ajax use use the data-ajax attribute.

If data-ajax is true or 'auto' then the library will look for the data-ajax-update and data-ajax-mode to decide the behavior.

The data-ajax-update method is a css selector pointing to an individual element, this will be used as a reference point for the response to the form submission.

The data-ajax-mode attribute determines what to do with the response to the submitted form in relation to the element referenced by the data-ajax-update attribute.

Ajax MethodBehavior
BeforeInsert the response from the server before the element
AfterInsert the response from the server after the element
Replace-Withreplace the element with the response from the server
UpdateUpdate the contents of the element with the response from the server

if there is no data-ajax-mode attribute the default is Update.

An example may look like this:

<div id="form-container">
  <form method="post" data-ajax="true" data-ajax-mode="replace" data-ajax-update="#form-container" >
    <!-- form contents -->
    </form>
</div>

The library will submit the form using the method specified against the form, and will expect an html partial as a response.

Form redirection

If you wish to redirect your form to a new page upon submission i would suggest using a non-ajax form, however if for whatever reason you are unable to do so, you may return a json response that will redirect to a new page, the json must be an exact match to the following example, the redirectTo property will be the url to which you wish to redirect the user.

{
  "redirectTo": "/contact-us/success" 
}

Manual Async Forms

If you have a form you want to handle manually you can remove the data-ajax-mode and the data-ajax-update attribute and set the data-ajax property to 'manual' i.e.

<div>
  <form method="post" id="my-form" data-ajax="manual">
    <!-- form contents -->
    </form>
</div>

This form can then be handled via javascript as follows.

const form = document.querySelector('#my-form')

form.addEventListener('submit', function() {
  form.validator.validateForm().then(function(formData) {
    // form has successfully validated.
    // form data is a javascript FormData object
    // form can now be submitted via fetch or whatever is desired.

    // the form can be converted to a json object by calling the following
    const formJson = form.validator.formToObject()

  }).catch(function(errors, fields) {
    // handle any errors here as desired.
  })
})
1.0.61

27 days ago

1.0.60

27 days ago

1.0.59

1 month ago

1.0.58

1 month ago

1.0.57

2 months ago

1.0.56

2 months ago

1.0.55

3 months ago

1.0.54

3 months ago

1.0.53

3 months ago

1.0.48

3 months ago

1.0.47

3 months ago

1.0.49

3 months ago

1.0.51

3 months ago

1.0.50

3 months ago

1.0.52

3 months ago

1.0.46

4 months ago

1.0.45

4 months ago

1.0.44

4 months ago

1.0.39

10 months ago

1.0.38

10 months ago

1.0.40

8 months ago

1.0.43

7 months ago

1.0.42

7 months ago

1.0.37

10 months ago

1.0.36

1 year ago

1.0.35

1 year ago

1.0.33

1 year ago

1.0.32

1 year ago

1.0.34

1 year ago

1.0.31

1 year ago

1.0.29

1 year ago

1.0.28

1 year ago

1.0.30

1 year ago

1.0.18

1 year ago

1.0.17

1 year ago

1.0.27

1 year ago

1.0.16

1 year ago

1.0.26

1 year ago

1.0.25

1 year ago

1.0.15

1 year ago

1.0.14

1 year ago

1.0.13

1 year ago

1.0.12

1 year ago

1.0.9

1 year ago

1.0.8

1 year ago

1.0.7

1 year ago

1.0.6

1 year ago

1.0.5

1 year ago

1.0.11

1 year ago

1.0.10

1 year ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago