@welton-dev/react-class-validator
v1.2.1
Published
React hook for validation with class-validator
Downloads
3
Maintainers
Readme
react-class-validator
Easy-to-use React hook for validating forms with the class-validator library.
Installation
npm install --save react-class-validator
const validatorOptions: ValidatorContextOptions = {
onErrorMessage: (error): string => {
// custom error message handling (localization, etc)
}
}
render((
<ValidatorProvider options={validatorOptions}>
<MyComponent />
</ValidatorProvider>
), document.getElementById('root'))
Default onErrorMessage behavior
The default behavior is to flatten all error constraints for each attribute.
const _getDefaultContextOptions = (): ValidatorContextOptions => ({
onErrorMessage: (error) => Object.keys(error.constraints).map((key) => error.constraints[key])
});
Usage
import { IsNotEmpty, IsEmail } from "class-validator";
class LoginValidation {
@IsNotEmpty({
message: 'username cannot be empty'
})
public username: string;
@IsNotEmpty({
message: 'password cannot be empty'
})
public password: string;
@IsEmail({
message: 'Enter valid email'
})
public email: string
}
const MyComponent = () => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [email, setEmail] = useState('');
const [validate, errors] = useValidation(LoginValidation);
return (
<form onSubmit={async (evt) => {
evt.preventDefault();
// `validate` will return true if the submission is valid
if (await validate({username, password, email})) {
// ... handle valid submission
}
//(Optional) `validate` returns true if the submitted filter is valid
if (await validate({username, password}, ["username", "password"])) {
// ... handle valid submission
}
}}>
{/* use a filter so that the onBlur function will only validate username */}
<input
value={username}
onChange={({target: {value}}) => setUsername(value)}
onBlur={() => validate({username}, ['username'])}
valid={async () => await validate({username}, ['username'])} //(Optional) return true for valid username filter
/>
{/* show error */}
{errors.username && (
<div className="error">
{errors.username.map((message) => <strong>message</strong>)}
</div>
)}
</form>
);
};
Contributors
Library built and maintained by Robin Schultz Contributor Welton Castro
If you would like to contribute (aka buy me a beer), you can send funds via PayPal at the link below.