Validater
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
}
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')
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)
.
A array that type is ValidaterRule
.
name: string
strategy: any
message?: string
type: 'string' | 'boolean' | 'number'
trim: boolean
defaultMessage: string
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('')
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 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')
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
.
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')
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) {
}
}, [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