1.5.1 • Published 1 year ago

@hitpixel/validation v1.5.1

Weekly downloads
-
License
ISC
Repository
-
Last release
1 year ago

Form Validation Library

Quickly add javascript validation to your HTML form, using a jquery-like configuration object. It comes with built-in error messages and locale options. The validation options include:

  • Credit Card Numbers
  • Credit Card Types
  • Email
  • Full Name
  • Minimum and Maximum
  • Required

You can also

  • Create your own custom validation functions
  • Use your own custom validation error messages

Finally, you can add extra functionality to your form inputs using these pre-built options:

  • Email format suggestion tooltip
  • Disable invalid calendar dates for card expiry
  • Format credit card numbers with spaces between numbers

Get Started

Step 1: Installation

For web environments requiring a <script> tag, one option is to use UNPKG for the CDN hosted minified file:

Include the script in your html, like this. Make sure you edit the version to the latest eg @1.2.0

 <script src="https://unpkg.com/@hitpixel/validation@1.5.0/dist/index.umd.js"></script>

OR

Grab the index.umd.js file from the dist folder and add it your web files. Include the script in your html, like this:

 <script src="./index.umd.js"></script>

OR

Import it using NPM. The package supports both commonjs for Node environments, and ES modules. Include the script in your html, like this:

npm install @hitpixel/validation

And then import the file:

import { hpForm } from '@hitpixel/validation';

Step 2: Initialise the form

In a client side script, you can access the library from the The library is added to the global window object under the following name: customFormValidator. This is a function which takes a configuration object as an argument, and returns two functions: 1. validate() - triggers a validation-check. To use conditionally in the form submit handler. 2. errorFocus() - will focus on the first input with an error

EXAMPLE - Validation while user types (no validation after submit)

Simply intialise the form with hitpixelValidator to validate while user types`

const config = {}; // OBJECT WITH CONFIGURATION
const form = document.getElementById('form')
if (window.hpForm) window.hpForm(form, config);

// The form is now initialised, and validation error messages will show when user types
// NOTE this will not prevent the user from submitting form

EXAMPLE - Validation after user submits

const config = {...}; // OBJECT WITH CONFIGURATION
const form = document.getElementById('form')
if (window.hpForm){
    const { validate, errorFocus } = window.hpForm(form, config);
    
    form.addEventListener('submit', (e) => {
        e.preventDefault();
        if (!validate()) return errorFocus();

        //... submit to server, etc
    })
}

Configuration object

  • Each object key must match the input name.
  • The value for the key is an object, with a validations key. This is always an array, which can either be an array of strings, for each type of validation. eg ['isRequired', 'isCreditCard' ]
  • OR it can take an object, in place of the string, for further configuration

Example

    const config = {
        name: {
            validations: ['isRequired'],
        },
        email: {
          validations: ['isRequired', { type: 'isEmail', error: 'Displaying a custom message',}]
        }
    };

Configuration options and default error messages

  • isRequired This field is required.
  • isCvvValid - checks CVV is 3 digits Incorrect CVV
  • isValidEmail This not a valid email address
  • isMasterVisa Only Visa and Mastercard are accepted.
  • isAfterCurrentDate - Checks if a date selected is not in the past Please set a valid date
  • isMin You have not reached the minimum requirement.
  • isValidName - expects at least two alpha strings separated by a space Please supply your name exactly as it appears on your card.
  • isValidCreditCardNumber Invalid card number..
  • termsAccepted - expects a selected checkbox You must accept the terms and conditions.
  • custom - for custom validation functions Error

Adding custom error message in HTML

If you would prefer to add your custom error message in the HTML rather than in the configuration object, simply use a data attribute in the input:

    <input data-custom-error="This is a custom error message" name="email" >

Note this will override all locale translations.

Adding a custom validation function

If you need some custom validation logic instead of one of the default validation options, create a function that returns a boolean. The function will always receive the string as an argument.

    const config = {
        name: {
            validations: [
                {
                    type: 'custom',
                    error: 'Your name must start with the letter b',
                    customValidator: ( str ) => str[0] === 'b',
                },
            ],
        }
    }

Adding input configuration

This library does not only validate. It also provides default options for giving inputs extra functionality, such as formating a credit card number input. Like the validations, this is an array which takes string identifiers.

Example

    const config = {,
        email: {
            validations: ['isRequired', 'isEmail'],
            configurations: ['showEmailSuggestions'],
        }
    };

Default configurations

setCardExpireyOptions Applies to payment page forms. If there are select boxes for month and year expiry, this prevents a user selecting a month in the past. Restrictions:

  • The input name for the month select element MUST be expires_month.

cardNumberFormatter This will automatically add appropriate spacing between numbers inside an input which takes a credit card number;

showEmailSuggestions Using the mailcheck library, it provides suggestions for possible misspelt emails eg gnail.com

For Development

There is a dev server configured with a mock form. You can find this configuration in src/devServer

For Distribution and Production

Follow these steps to build a new bundled file

  1. First, ensure Node and NPM are installed
  2. Clone to repo and install all dependencies
  3. Run npm run test to perform tests
  4. Run npm run build:types to build a compiled .d.ts file containing all the project types in the dist folder
  5. Run npm run build to generates .umd, .esm and .cjs files
  6. The bundled javascript file can be found in the /dist folder

Publishing to NPM

  1. Run npm login and follow the prompts
  2. Run npm publish