1.5.1 • Published 7 months ago

@universal-packages/validations-react v1.5.1

Weekly downloads
-
License
MIT
Repository
github
Last release
7 months ago

Validations React

npm version Testing codecov

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.

License

MIT licensed.

1.5.1

7 months ago

1.5.0

7 months ago

1.4.1

7 months ago

1.4.0

7 months ago

1.3.0

7 months ago

1.2.0

7 months ago

1.1.1

7 months ago

1.1.0

7 months ago

1.0.0

7 months ago