An excellent and useful JavaScript validation library, it works better with the Validator.js.
npm install --save @flcwly/validaterYou can Using the Validater to check any data, like string and others.
Firstly, you need extend the Validator plugins as your need.
constValidater=require('@flcwly/validater').defaultconstrequiredPlugin=(value: any,strategy=true)=>{returnstrategy&&!!value}constmaxPlugin=(value: string,strategy: number)=>{returnrequired(value)&&value.length<=strategy}// extendValidater.extend('required',requiredPlugin).extend('max',maxPlugin)Secondly, you can Using the required and max like the following way.
constv=newValidater([{name: 'required',strategy: true,message: 'please enter your name.',},{name: 'max',strategy: 11,message: 'Please enter the correct name.',},])consterrorMsg=v.validateOne('abc1234567890')// "Please enter the correct name."You can define the order of validators by array.
or using ES6 Module:
importValidaterfrom'@flcwly/validater'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 validationmessage?: string// rule error messageoptions
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.
constdefaultRuleMessage='required defaultRuleMessage'Validater.extend('required',requiredPlugin).extend('max',maxPlugin,defaultRuleMessage)constv=newValidater([{name: 'required',strategy: true,},])consterrorMsg=v.validateOne('')// "required defaultRuleMessage"If you don't set a defaultRuleMessage when extend, Then will using the defaultMessage.
constv=newValidater([{name: 'required',strategy: true,},])consterrorMsg=v.validateOne('')// "The value is incorrect"The message string's relationship for overriding is:
message > defaultRuleMessage > defaultMessageAnd the message string is parsed and replaced with the value by $0.
constv=newValidater([{name: 'numeric',strategy: true,message: '$0 error',},])consterrorMsg=v.validateOne('1a1')// "1a1 error"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.
It works better with the Validator.js.
importValidatorfrom'validator'Validater.extend('isEmail',Validator.isEmail)constv=newValidater([{name: 'isEmail',message: '"$0" error',},])consterrorMsg=v.validateOne('@mail.com')// ""@mail.com" error"You can use Validater with React hooks like the following usage. Here is a CodeSandbox Demo.
importReact,{useState,useCallback,useMemo}from'react'importValidaterfrom'@flcwly/validater'importValidatorfrom'validator'constrequiredPlugin=(value: any,strategy=true)=>{returnstrategy&&!Validator.isEmpty(value)}constpatternPlugin=(value: string,strategy: RegExp)=>{returnrequiredPlugin(value)&&strategy.test(value)}Validater.extend('required',requiredPlugin).extend('pattern',patternPlugin)exportconstuseValidater=(initialValue: any,rules: any[])=>{const[value,setValue]=useState(initialValue)const[error,setError]=useState()const[verified,setVerified]=useState(!rules)constvalidater=useMemo(()=>newValidater(rules),[rules])constverify=useCallback((val=value)=>{consterrorMsg=validater.validateOne(val)setVerified(true)setError(errorMsg)returnerrorMsg},[value,setError,setVerified,validater])return[value,setValue,error,verify,verified]}exportfunctionInputTestComponent(){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',},])constbtnDisabled=useMemo(()=>{return!!phoneError||!hasVerifiedPhone},[phoneError,hasVerifiedPhone])consthandleSubmit=useCallback(async()=>{constphoneErrorMsg=phoneError||verifyPhone()if(phoneErrorMsg){// deal with error here...}// request to submit},[phoneError,verifyPhone])return(<div><div>
Phone number:
<inputvalue={phone}onChange={(e)=>{constval=e.target.valuesetPhone(val)verifyPhone(val)}}onBlur={()=>verifyPhone()}/></div><div>
Error:
<span>{hasVerifiedPhone ? phoneError||'No Error.' : 'Initial Status.'}</span></div><buttondisabled={btnDisabled}onClick={handleSubmit}>
Submit
</button></div>)}You can find all cases in files:/test/*.spec.js, And testing Using below script.
npm run test