@universal-packages/validations-react
v1.5.1
Published
React bindings for universal validations
Downloads
396
Readme
Validations React
React bindings for Universal Validations, to use validations also in React applications.
Install
npm install @universal-packages/validations-react
Validations react uses exclusively teh react hooks API so make sure you are using a recent version of React.
Hooks
useValidation(attributes: Object, Validation: ValidationClass)
It validates the attributes every time they change, and returns the validation result. The values when first called the hook will be considered as the initial values.
import { useValidation } from '@universal-packages/validations-react'
import FormValidation from './FormValidation'
const HappyComponent = () => {
const [name, setName] = useState('david')
const validation = useValidation({ name }, FormValidation)
const handleSubmit = () => {
if (validation.isValid) {
api.post('/users', { name }).then((data) => {
if (data.status === 'success') {
console.log('User created')
} else {
// Now we know the backend does not like the current name value so wer do not admit it again
// In other words we do not send the same request again
validation.setKnownErrors({ name: [data.validation.errors.name] })
}
})
} else {
validation.setShowErrors(true)
}
}
return (
<div>
<input value={name} onChange={(e) => setName(e.target.value)} />
<button onClick={handleSubmit}>Submit</button>
{!validation.isValid && validation.showErrors && (
<div>
{validation.errors.name.map((error) => (
<span>{error}</span>
))}
</div>
)}
</div>
)
}
Typescript
This library is developed in TypeScript and shipped fully typed.
Contributing
The development of this library happens in the open on GitHub, and we are grateful to the community for contributing bugfixes and improvements. Read below to learn how you can take part in improving this library.