https://github.com/anigenero/react-class-validator
React hook for validating forms with class-validator
https://github.com/anigenero/react-class-validator
class-validator formik-validation react typescript validation validator
Last synced: 10 months ago
JSON representation
React hook for validating forms with class-validator
- Host: GitHub
- URL: https://github.com/anigenero/react-class-validator
- Owner: anigenero
- License: mit
- Created: 2020-05-11T14:28:45.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2023-10-12T18:11:55.000Z (over 2 years ago)
- Last Synced: 2024-11-08T05:32:17.219Z (over 1 year ago)
- Topics: class-validator, formik-validation, react, typescript, validation, validator
- Language: TypeScript
- Homepage:
- Size: 1.56 MB
- Stars: 13
- Watchers: 1
- Forks: 5
- Open Issues: 6
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# react-class-validator
Easy-to-use React hook for validating forms with the [class-validator](https://github.com/typestack/class-validator) library.
[](https://github.com/anigenero/react-class-validator/actions/workflows/build.yml)
[](https://codecov.io/gh/anigenero/react-class-validator)
## Installation
```bash
npm install --save react-class-validator
```
```typescript jsx
const validatorOptions: ValidatorContextOptions = {
onErrorMessage: (error): string => {
// custom error message handling (localization, etc)
},
resultType: 'boolean' // default, can also be set to 'map'
}
render((
), document.getElementById('root'))
```
## Default onErrorMessage behavior
The default behavior is to flatten all error constraints for each attribute.
```typescript
const getDefaultContextOptions = (): ValidatorContextOptions => ({
onErrorMessage: (error) => Object.keys(error.constraints).map((key) => error.constraints[key])
});
```
### react-intl
When using libraries such as [react-intl](https://github.com/formatjs/formatjs), you don't have to modify the existing
`onErrorMessage` handler. Decorators are handled at source load, so you only need to include the `intl.formatMessage` in your message definition.
```typescript
class Person {
@IsEmail({}, {
message: intl.formatMessage(defineMessage({defaultMessage: 'Invalid email'}))
})
@IsNotEmpty({
message: intl.formatMessage(defineMessage({defaultMessage: 'Email cannot be empty'}))
})
public email: string;
}
```
## Usage
Create a class using validation decorators from `class-validator`.
```typescript
import { IsNotEmpty } from "class-validator";
class LoginValidation {
@IsNotEmpty({
message: 'username cannot be empty'
})
public username: string;
@IsNotEmpty({
message: 'password cannot be empty'
})
public password: string;
}
```
Set up your form component to validate using your validation class.
```typescript jsx
const MyComponent = () => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [validate, errors] = useValidation(LoginValidation);
return (
{
evt.preventDefault();
// `validate` will return true if the submission is valid
if (await validate({username, password})) {
// ... handle valid submission
}
}}>
{/* use a filter so that the onBlur function will only validate username */}
setUsername(value)}
onBlur={() => validate({username}, ['username'])}/>
{/* show error */}
{errors.username && (
{errors.username.map((message) => message)}
)}
);
};
```
## Usage With Formik
`react-class-validator` easily integrates with [Formik](https://formik.org/). You can simply use the `validate`
function returned from `useValidation`, so long as the Formik fields are named the same as the keys in your validation
class. Individual fields will have to be validated with `onBlur` functionality.
### Formik error messages
To display error messages without custom handling, messages will need to be outputted as a map upon validation.
Do this by overriding the default `resultType` (you can also do this at the component-level).
```typescript
const options: ValidatorContextOptions = {
resultType: 'map'
};
```
Then you can simply integrate with the default Formik flow.
```typescript jsx
export const Login: FunctionComponent = () => {
const [validate] = useValidation(LoginValidation);
return (
{({values, touched, errors, handleChange, handleBlur}) => (
Username
{errors.username && touched.username ? (
{errors.username}
) : null}
{/* other fields */}
Submit
)}
);
};
```
## Contributors
Library built and maintained by [Robin Schultz](http://anigenero.com)
If you would like to contribute (aka buy me a beer), you can send funds via PayPal at the link below.
[](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=SLT7SZ2XFNEUQ)