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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@mhub/web-validations

v0.1.12

Published

MHub web validations

Downloads

36

Readme

MHub Web validations

How to use this package

  1. Install package

    npm install @mhub/web-validations --save
  2. Usage:

    import React from 'react';
    import { validate, required } from '@mhub/web-validations';
    
    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          value: '',
          hasError: false,
          message: null,
        };
      }
      handleOnChange = (event) => {
        const inputValue = event.target.value;
        const inputName = event.target.name;
        validate({
          value: inputValue,
          name: inputName,
          label: 'Name',
          validations: [required],
        }).then((result) => {
          // do anything with validation result
          this.setState({
            value: inputValue,
            hasError: !result.isValid,
            message: result.message,
          });
        });
      }
      render() {
        return (
          <div>
            <input
              type="text"
              name="name"
              value={this.state.value}
              onChange={this.handleOnChange}
            />
            {
              this.state.hasError ? (
                <div className="helper">
                  {this.state.message}
                </div>
              ) : null
            }
          </div>
        );
      }
    }
    
    React.render(<App />, document.getElementById('app'));

Utils & Validators available

| Functions | Utils | Validators | | --- | --- | --- | | validate | assertArray | arrayLength | | | assertObject | capitalize | | | assertShape | email | | | assertNumber | equalTo | | | assertString | identity | | | assertStringOrNumber | isAlpha | | | createValidity | matchRegex | | | | numericRange | | | | phonePrefix | | | | phoneNumber | | | | required | | | | stringLength |


Functions:

validate({ value, name, message, label, validations })

  • return a Promise with object({ key, isValid, message })
  • Usage:
    validate({
      value: 'input-value',
      name: 'key',
      message: 'custom error message',
      label: 'Label use in message', // doesn't use in custom message
      validations: [
        // validations props accept function and object:
        // - validator function
        required,
        // - expand validator function
        (value, options) => stringLength(value, {
          ...options,
          // some validators has extra options
          min: 5,
          // you can override props too
          label: 'Use this label instead',
        }),
        // - object format
        {
          validate: stringLength,
          options: {
            // some validators has extra options
            min: 5,
            // you can override props too
            label: 'Use this label instead',
          },
        }
      ],
    }).then((result) => {
      // const { key, isValid, message } = result;
      // do something with the result
      console.log(result);
    });

Utils:

* label parameter is used to identify variable name

assertArray(value, label)

  • check whether value is an array
  • Usage:
    // pass
    assertArray(['Max', 'Jack'], 'children');
    
    // fail
    assertArray('Max', 'children');
    // TypeError: children needs to be an array

assertObject(value, label)

  • check whether value is a plain object
  • Usage:
    // pass
    const car = {
      brand: 'test',
      weight: '20kg',
    };
    assertObject(car, 'car');
    
    // fail
    assertObject('Special car', 'car');
    // TypeError: car needs to be a plain object

assertShape(value, keys, label)

  • check whether value is a plain object
  • check if object keys match keys
  • Usage:
    const car = {
      brand: 'test',
      weight: '20kg',
    };
    // pass
    assertShape(car, ['brand', 'weight'], 'car');
    
    // fail;
    assertShape(car, ['wheel'], 'car');
    // TypeError: car's 'keys' does not matched with keys: wheel

assertNumber(value, label)

  • check whether value is a number
  • Usage:
    // pass
    assertNumber(15, 'age');
    
    // fail
    assertNumber('15', 'age');
    // TypeError: age needs to be a number

assertString(value, label)

  • check whether value is a string
  • Usage:
    // pass
    assertString('My name', 'name');
    
    // fail
    assertString(1234, 'name');
    // TypeError: name needs to be a string

assertStringOrNumber(value, label)

  • check whether value is a string or number
  • Usage:
    // pass
    assertStringOrNumber('My name', 'name');
    assertStringOrNumber(15, 'age');
    
    // fail
    assertStringOrNumber(['Max', 'Jack'], 'children');
    // TypeError: name needs to be a string or number

createValidity(key)

  • return an object with validity status
  • Usage:
    const validity = createValidity('name');
    console.log(validity);
    // output:
    // {
    //   key: 'name',
    //   isValid: true,
    // }

Validators:

arrayLength

  • validate value to match minimum / maximum / equal range requirement
  • Option:

| Name | Type | Default | | --- | --- | --- | | ...common options | | min | number | 0 | | max | number | value.length | | equal | number | 0 |

  • Usage:
    // used in validate's validations
    validate({
      validations: [
        // expand validator function
        (value, options) => arrayLength(value, {
          ...options,
          min: 0,
          max: 5,
        }),
      ],
    })
    
    // standalone
    // arrayLength(value, { key, label, message, min, max, equal })
    const children = ['Max', 'Jack'];
    const validity = arrayLength(children, {
      key: 'children',
      label: 'Children',
      min: 0,
      max: 5,
    });
    console.log(validity);
    // output:
    // {
    //   key: 'children',
    //   isValid: true,
    //   message: undefined,
    // }

capitalize

  • check whether value is fully capitalized, e.g. ABC
  • Option:

| Name | Type | Default | | --- | --- | --- | | ...common options |

  • Usage:
    // used in validate's validations
    validate({
      validations: [
        capitalize,
      ],
    })
    
    // standalone
    // capitalize(value, { key, label, message })
    const code = 'ABC';
    const validity = capitalize(code, {
      key: 'code',
      label: 'Receipt Code',
    });
    console.log(validity);
    // output:
    // {
    //   key: 'code',
    //   isValid: true,
    //   message: undefined,
    // }

email

  • validate value to match email format
  • Option:

| Name | Type | Default | | --- | --- | --- | | ...common options | | validRegex | string or Regexp | RX_EMAIL |

  • Usage:
    // used in validate's validations
    validate({
      validations: [
        email,
      ],
    })
    
    // standalone
    // email(value, { key, label, message, validRegex })
    const email = '[email protected]';
    const validity = email(email, {
      key: 'email',
      label: 'Email Address',
    });
    console.log(validity);
    // output:
    // {
    //   key: 'email',
    //   isValid: true,
    //   message: undefined,
    // }

equalTo

  • validate value to match target value
  • Option:

| Name | Type | Default | | --- | --- | --- | | ...common options | | target | object { label, value } | { label: 'Target', value } |

  • Usage:
    const confirmPassword = 'password';
    
    // used in validate's validations
    validate({
      validations: [
        // expand validator function
        (value, options) => equalTo(value, {
          ...options,
          target: {
            label: 'Confirm Password',
            value: confirmPassword,
          }
        }),
      ],
    })
    
    // standalone
    // equalTo(value, { key, label, message, target* })
    const password = 'password';
    const validity = equalTo(password, {
      key: 'password',
      label: 'Password',
      target: {
        label: 'Confirm Password',
        value: confirmPassword,
      }
    });
    console.log(validity);
    // output:
    // {
    //   key: 'password',
    //   isValid: true,
    //   message: undefined,
    // }

identity

  • validate value to match identity format based on country code and identity type
  • Option:

| Name | Type | Default | | --- | --- | --- | | ...common options | | validRegex | string or Regexp | ^\\w*$ | | identityType | string | *Required | | countryCode | string | *Required |

  • Usage:
    // used in validate's validations
    validate({
      validations: [
        // expand validator function
        (value, options) => identity(value, {
          ...options,
          identityType: 'ic_number',
          countryCode: 'MY',
        }),
      ],
    })
    
    // standalone
    // identity(value, { key, label, message, validRegex, identityType*, countryCode* })
    const identity = '1234567890';
    const validity = identity(identity, {
      key: 'identity',
      label: 'Identity',
      identityType: 'ic_number',
      countryCode: 'MY',
    });
    console.log(validity);
    // output:
    // {
    //   key: 'identity',
    //   isValid: true,
    //   message: undefined,
    // }

isAlpha

  • validate value to have only alphabet
  • Option:

| Name | Type | Default | | --- | --- | --- | | ...common options | | validRegex | string or Regexp | RX_ALPHA |

  • Usage:
    // used in validate's validations
    validate({
      validations: [
        isAlpha,
      ],
    })
    
    // standalone
    // isAlpha(value, { key, label, message, validRegex })
    const name = 'Jack';
    const validity = isAlpha(name, {
      key: 'name',
      label: 'Name',
    });
    console.log(validity);
    // output:
    // {
    //   key: 'name',
    //   isValid: true,
    //   message: undefined,
    // }

matchRegex

  • validate value to match validRegex format
  • Option:

| Name | Type | Default | | --- | --- | --- | | ...common options | | validRegex | string or Regexp | .* |

  • Usage:
    // used in validate's validations
    validate({
      validations: [
        // expand validator function
        (value, options) => matchRegex(value, {
          ...options,
          validRegex: '^abc$',
        }),
      ],
    })
    
    // standalone
    // matchRegex(value, { key, label, message, validRegex });
    const value = 'abc';
    const validity = matchRegex(value, {
      key: 'passcode',
      label: 'Passcode',
      validRegex: '^abc$',
    });
    console.log(validity);
    // output:
    // {
    //   key: 'passcode',
    //   isValid: true,
    //   message: undefined,
    // }

numericRange

  • validate value to match minimum / maximum requirement
  • Option:

| Name | Type | Default | | --- | --- | --- | | ...common options | | min | number | 0 | | max | number | value |

  • Usage:
    // used in validate's validations
    validate({
      validations: [
        // expand validator function
        (value, options) => numericRange(value, {
          ...options,
          min: 1,
          max: 100,
        }),
      ],
    })
    
    // standalone
    // numericRange(value, { key, label, message, min, max })
    const age = 15;
    const validity = numericRange(age, {
      key: 'age',
      label: 'Age',
      min: 1,
      max: 100,
    });
    console.log(validity);
    // output:
    // {
    //   key: 'age',
    //   isValid: true,
    //   message: undefined,
    // }

phonePrefix

  • validate value to match phone prefix number based on country code
  • Option:

| Name | Type | Default | | --- | --- | --- | | ...common options | | validRegex | string or Regexp | ^60$\|^62$\|^65$ | | countryCode | string | - |

  • Usage:
    // used in validate's validations
    validate({
      validations: [
        // expand validator function
        (value, options) => phonePrefix(value, {
          ...options,
          countryCode:'MY',
        }),
      ],
    })
    
    // standalone
    // phonePrefix(value, { key, label, message, validRegex, countryCode })
    const office = 15;
    const validity = phonePrefix(mobile_prefix, {
      key: 'mobile_prefix',
      label: 'Mobile Prefix',
      countryCode:'MY',
    });
    console.log(validity);
    // output:
    // {
    //   key: 'mobile_prefix',
    //   isValid: true,
    //   message: undefined,
    // }


phoneNumber

  • validate value to match phone number format based on prefix and type
  • Option:

| Name | Type | Default | | --- | --- | --- | | ...common options | | validRegex | string or Regexp | ^\\d+$ | | phonePrefix | string | *Required | | isMobile | boolean | false |

  • Usage:
    // used in validate's validations
    validate({
      validations: [
        // expand validator function
        (value, options) => phoneNumber(value, {
          ...options,
          phonePrefix:'60',
        }),
      ],
    })
    
    // standalone
    // phoneNumber(value, { key, label, message, validRegex, phonePrefix, isMobile })
    const office = 15;
    const validity = phoneNumber(office, {
      key: 'office',
      label: 'Office number',
      phonePrefix:'60',
    });
    console.log(validity);
    // output:
    // {
    //   key: 'office',
    //   isValid: true,
    //   message: undefined,
    // }

required

  • validate value to have data
  • Option:

| Name | Type | Default | | --- | --- | --- | | ...common options |

  • Usage:
    // used in validate's validations
    validate({
      validations: [
        required,
      ],
    })
    
    // standalone
    // required(value, { key, label, message })
    const name = 'Jack';
    const validity = required(name, {
      key: 'name',
      label: 'Name',
    });
    console.log(validity);
    // output:
    // {
    //   key: 'name',
    //   isValid: true,
    //   message: undefined,
    // }
    

stringLength

  • validate value to match minimum / maximum / equal requirement
  • Option:

| Name | Type | Default | | --- | --- | --- | | ...common options | | min | number | 0 | | max | number | value.length | | equal | number | 0 |

  • Usage:
    // used in validate's validations
    validate({
      validations: [
        // expand validator function
        (value, options) => stringLength(value, {
          ...options,
          min: 1,
          max: 10,
        }),
      ],
    })
    
    // standalone
    // stringLength(value, { key, label, message, min, max, equal })
    const name = 'Long Name';
    const validity = stringLength(name, {
      key: 'name',
      label: 'Name',
      min: 1,
      max: 10,
    });
    console.log(validity);
    // output:
    // {
    //   key: 'name',
    //   isValid: true,
    //   message: undefined,
    // }

Common option:

Name | Type | Defaults --- | --- | --- key | string | - label | string | 'Field' message | string or function | (decided by validators)

Note: message now can be a function() that return string OR just string itself

// Example
let message;
// function return string
message = (validatorOptions) => {
  // required validator example
  return `${validatorOptions.label} is required`;
}
// string
message = 'Password is required';

Getting started for development

  1. Clone repo

    git clone [email protected]:TheRedBricks/mhub-web-validations.git
  2. Install

    npm install
  3. Run tests

    npm run test -- --watch