@validator.tool/hook
v2.2.6
Published
Hooks for use with `validator.tool`.
Downloads
121
Maintainers
Readme
@validator.tool/hook
Hooks for use with validator.tool
.
Install
$ npm install @validator.tool/hook --save
Usage
import { useEffect, useState, Fragment } from 'react';
import { useValidator } from '@validator.tool/hook';
export default function Demo() {
const [data, setData] = useState({
email: '[email protected]'
});
const { validator, handleReset, handleSubmit } = useValidator({
initValues: data,
});
const onSubmit = (value) => {
console.log('value', value)
}
const onReset = (value) => {
setData({ ...value });
}
function handleChange(env) {
const target = env.target;
const value = target.type === "checkbox" ? target.checked : target.value;
const name = target.name;
setData({ ...data, [name]: value });
}
return (
<form
onSubmit={handleSubmit(onSubmit)}
onReset={handleReset(onReset)}
onChange={handleChange}
onBlur={handleChange}
>
<div>
<label htmlFor="email">EMail:</label>
<input type="email" name="email" defaultValue={data.email} />
<span>
{validator.message('email', data.email, {
validate: (val) => !/^[A-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(val) ? `The ${val} must be a valid email address.` : ''
})}
</span>
</div>
<div>
<label htmlFor="password">Password:</label>
<input type="password" name="password" />
<span>
{validator.message('password', data.password, {
validate: (val) => !val ? 'Please enter the password!' : ''
})}
</span>
</div>
<div style={{ width: '100%' }}>
<button type="submit">Submit</button>
<button type="reset">Reset</button>
</div>
</form>
);
}
API
import Validator, { ValidatorOption, Values } from 'validator.tool';
export * from 'validator.tool';
export interface UseValidator extends ValidatorOption {}
export declare function useValidator(props?: UseValidator): {
validator: Validator;
forceUpdate: () => void;
/** Only `Form` Support */
handleSubmit: (handle?: ((value: Values, valid: boolean) => void) | undefined) => (evn: React.FormEvent<HTMLFormElement>) => void;
/** Only `Form` Support */
handleReset: (handle?: ((value: Values) => void) | undefined) => (evn: React.FormEvent<HTMLFormElement>) => void;
};
Related
- validator.tool Lightweight JavaScript form validation, that had minimal configuration and felt natural to use.
License
Licensed under the MIT License.