npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@hitpixel/validation

v1.5.1

Published

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:</br>

Downloads

11

Readme

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/[email protected]/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