npm install use-validation-hooks
use-validation
is a small validation library (1.2kb gzipped), created to provide basic validators for some of the most common usages.
Validation Result is error message or null
Besides these core validators that come with the package, you can always extend some validators or create specialization of one. That is how useEmailValidator
or useUrlValidator
are created;
import { useStringValidator } from "./useStringValidator";
import { RequiredValidatorProps } from "./useRequiredValidator";
const emailRegex: RegExp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
export const useEmailValidator = ({
label,
required = true
}: RequiredValidatorProps): ((value: string) => string | null) => {
return useStringValidator({ label, required, regex: emailRegex });
};
useEmailValidator: ({ label, required }: RequiredValidatorProps) => (value: string) => string | null;
useDateValidator: ({ label, required, min, max, between }: DateValidatorProps) => (value: Date) => string | null;
useFileValidator: ({ label, required, max, allowedExtensions }: FileValidatorProps) => (value: File) => string | null;
useNumberValidator: ({ label, required, min, max }: NumberValidatorProps) => (value: number) => string | null;
useRequiredValidator: ({ label, required }: RequiredValidatorProps) => (value: string | number | any[] | Date | File) => string | null;
useStringValidator: ({ label, required, min, max, regex }: StringValidatorProps) => (value: string) => string | null;
useUrlValidator: ({ label, required }: RequiredValidatorProps) => (value: string) => string | null;
- Value Validation
- Custom error message formats
- i18n support
import React, {useEffect, useState} from 'react'
import { useStringValidator } from 'use-validation-hooks'
export const App = () => {
const [name, setName] = useState('')
const [nameFieldError, setNameValidity] = useState(null)
const validateName = useStringValidator({ label: 'Name', required: true, min: 6, max: 12 });
const onNameChange = ({ target: { value } }) => setName(value);
useEffect(() => {
setNameValidity(validateName(name))
}, [name])
return (
<div>
<h1>{ !nameFieldError ? 'Name is VALID' : nameFieldError }</h1>
<input type={'text'} value={name} onChange={onNameChange} />
</div>
)
}
MIT © rasha08