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

@flcwly/validater

v0.1.4

Published

A excellent and useful JavaScript validation library, it works better with the Validator.js

Downloads

1

Readme

Validater

Build Status GitHub license npm version

A excellent and useful JavaScript validation library, it works better with the Validator.js.


Getting Started

Installation

npm install --save @flcwly/validater

Documentation

You can Using the Validater to check any data, like string and others.

Firstly, you need extend the Validator plugins as your need.

const Validater = require('@flcwly/validater').default
const requiredPlugin = (value: any, strategy = true) => {
  return strategy && !!value
}
const maxPlugin = (value: string, strategy: number) => {
  return required(value) && value.length <= strategy
}

// extend
Validater.extend('required', requiredPlugin).extend('max', maxPlugin)

Secondly, you can Using the required and max like the following way.

const v = new Validater([
  {
    name: 'required',
    strategy: true,
    message: 'please enter your name.',
  },
  {
    name: 'max',
    strategy: 11,
    message: 'Please enter the correct name.',
  },
])
const errorMsg = v.validateOne('abc1234567890') // "Please enter the correct name."

You can define the order of validators by array.

or using ES6 Module:

import Validater from '@flcwly/validater'

Constructor

The Validater constructor accepts two parameters: new Validater(rules, options).

  • rules: ValidaterRule[]

A array that type is ValidaterRule.

name: string      // extend ruleName for validation
strategy: any     // extend strategy for validation
message?: string  // rule error message
  • options
type: 'string' | 'boolean' | 'number' // transform type before validating, default is `string`
trim: boolean // trim(value) before validating when type is string, default is `true`
defaultMessage: string // default global error message, default is `The value is incorrect`,

If you have not set a specific error message for rule, the error message will using defaultRuleMessage.

const defaultRuleMessage = 'required defaultRuleMessage'
Validater.extend('required', requiredPlugin).extend('max', maxPlugin, defaultRuleMessage)

const v = new Validater([
  {
    name: 'required',
    strategy: true,
  },
])
const errorMsg = v.validateOne('') // "required defaultRuleMessage"

If you don't set a defaultRuleMessage when extend, Then will using the defaultMessage.

const v = new Validater([
  {
    name: 'required',
    strategy: true,
  },
])
const errorMsg = v.validateOne('') // "The value is incorrect"

The message string's relationship for overriding is:

message > defaultRuleMessage > defaultMessage

And the message string is parsed and replaced with the value by $0.

const v = new Validater([
  {
    name: 'numeric',
    strategy: true,
    message: '$0 error',
  },
])
const errorMsg = v.validateOne('1a1') // "1a1 error"

Instance Functions

  • addRules: (rules?: ValidaterRule[] | undefined) => void;

Traverse rules to register validators generated based on rules.

  • validate: (value: unknown, ruleName?: string | undefined) => string | void;

Validate a value with special ruleName.

  • validateOne: (value: unknown) => string | void;

Validate a value base on array order starts at 0.

  • validateAll: (value: unknown) => this;

Validate a value for all rules, then will return this.

  • hasError: () => boolean;

Check if the error exists, return true when error.

  • getError: (ruleName?: string | undefined) => any;

Get error to special ruleName, return all error as object when ruleName === undefined.


With validator.js

It works better with the Validator.js.

import Validator from 'validator'

Validater.extend('isEmail', Validator.isEmail)

const v = new Validater([
  {
    name: 'isEmail',
    message: '"$0" error',
  },
])
const errorMsg = v.validateOne('@mail.com') // ""@mail.com" error"

With React Hooks

You can use Validater with React hooks like the following usage. Here is a CodeSandbox Demo.

import React, { useState, useCallback, useMemo } from 'react'
import Validater from '@flcwly/validater'
import Validator from 'validator'

const requiredPlugin = (value: any, strategy = true) => {
  return strategy && !Validator.isEmpty(value)
}
const patternPlugin = (value: string, strategy: RegExp) => {
  return requiredPlugin(value) && strategy.test(value)
}

Validater.extend('required', requiredPlugin).extend('pattern', patternPlugin)

export const useValidater = (initialValue: any, rules: any[]) => {
  const [value, setValue] = useState(initialValue)
  const [error, setError] = useState()
  const [verified, setVerified] = useState(!rules)
  const validater = useMemo(() => new Validater(rules), [rules])

  const verify = useCallback(
    (val = value) => {
      const errorMsg = validater.validateOne(val)
      setVerified(true)
      setError(errorMsg)
      return errorMsg
    },
    [value, setError, setVerified, validater]
  )

  return [value, setValue, error, verify, verified]
}

export function InputTestComponent() {
  const [phone, setPhone, phoneError, verifyPhone, hasVerifiedPhone] = useValidater('', [
    {
      name: 'required',
      strategy: true,
      message: 'Please enter the phone number',
    },
    {
      name: 'pattern',
      strategy: /^[\d]{11}$/,
      message: 'Please enter the correct phone number',
    },
  ])
  const btnDisabled = useMemo(() => {
    return !!phoneError || !hasVerifiedPhone
  }, [phoneError, hasVerifiedPhone])
  const handleSubmit = useCallback(async () => {
    const phoneErrorMsg = phoneError || verifyPhone()
    if (phoneErrorMsg) {
      // deal with error here...
    }
    // request to submit
  }, [phoneError, verifyPhone])

  return (
    <div>
      <div>
        Phone number:
        <input
          value={phone}
          onChange={(e) => {
            const val = e.target.value
            setPhone(val)
            verifyPhone(val)
          }}
          onBlur={() => verifyPhone()}
        />
      </div>
      <div>
        Error:
        <span>{hasVerifiedPhone ? phoneError || 'No Error.' : 'Initial Status.'}</span>
      </div>
      <button disabled={btnDisabled} onClick={handleSubmit}>
        Submit
      </button>
    </div>
  )
}

Tests

You can find all cases in files:/test/*.spec.js, And testing Using below script.

npm run test