# use-validation

> Astonishingly easy form validation for React using hooks

Latest version **1.1.2** (published 2019-10-29) · MIT license · 0 weekly downloads

## Install

```sh
npm install use-validation
pnpm add use-validation
yarn add use-validation
bun add use-validation
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.1.2 |
| Published | 2019-10-29 |
| First published | 2018-11-04 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 0 |
| Unpacked size | 18.4 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 0 |
| Author | Matt Granmoe |
| Maintainers | granmoe |
| Keywords | javascript, react, form-validation, hooks, validation |

## Links

- npm: https://www.npmjs.com/package/use-validation
- Repository: https://github.com/granmoe/use-validation
- Issues: https://github.com/granmoe/use-validation/issues
- npm.io page: https://npm.io/package/use-validation

## Alternatives

- [mobx-react](https://npm.io/package/mobx-react.md) — 2.8M weekly downloads
- [rc-tree](https://npm.io/package/rc-tree.md) — 2.6M weekly downloads
- [@react-oauth/google](https://npm.io/package/@react-oauth/google.md) — 1.3M weekly downloads
- [@wagmi/connectors](https://npm.io/package/@wagmi/connectors.md) — 877.0K weekly downloads
- [vee-validate](https://npm.io/package/vee-validate.md) — 836.4K weekly downloads

## Recent versions

- 1.1.2 (latest) — 2019-10-29
- 1.1.0-beta.3 (beta) — 2019-09-13
- 1.1.1 — 2019-09-14
- 1.1.0 — 2019-09-14
- 1.1.0-beta.1 — 2019-09-13
- 1.1.0-beta.0 — 2019-09-13
- 1.0.1 — 2019-09-06
- 1.0.0 — 2019-07-28
- 0.4.0 — 2018-11-22
- 0.3.1 — 2018-11-12
- 0.3.0 — 2018-11-12
- 0.2.7 — 2018-11-10
- 0.2.6 — 2018-11-09
- 0.2.5 — 2018-11-08
- 0.2.4 — 2018-11-08
- … 5 more at https://npm.io/package/use-validation/versions

## README

# ✏️ ⚡️ Simple yet robust form validation for React ⚡️ ✏️

Offering the most concise and elegant form validation API known to humankind, without sacrificing performance.

_Weighing in at a whopping 1.1 kB gzipped and minified._

## Installation

`npm install use-validation`

or

`yarn add use-validation`

## Examples

### Simplest Case (a few simple inputs, default validation function)

```js
const { fields, handleSubmit } = useValidation({
  initialValues: { foo: '', bar: '' },
})

return (
  <Wrapper>
    <h1>Validation using hūX</h1>
    <form
      onSubmit={e => {
        e.preventDefault()
        handleSubmit()
      }}
    >
      <Input {...fields.foo} name="foo" />
      <Input {...fields.bar} name="bar" />
      <Button type="submit">Submit</Button>
    </form>
  </Wrapper>
)
```

_[Try this example on CodeSandbox!](https://codesandbox.io/embed/use-validation-basic-example-v1z03?fontsize=14&module=%2Fsrc%2Fexample.js)_

## API

### Input

It's one object with six properties (and only one is required).

This snippet shows the API in its entirety:

```js
const myValidationFunc = (
  { foo, bar },
  { someRandomThing, someOtherJunk },
) => ({
  foo:
    typeof foo !== 'number'
      ? 'Please enter a number'
      : foo === someOtherJunk
      ? `foo cannot be ${someOtherJunk}`
      : null,
  bar: bar === someRandomThing ? `bar cannot be ${someRandomThing}` : null,
})

const { fields, handleSubmit } = useValidation({
  initialValues: { foo: 'default value', bar: '' },
  validate: myValidationFunc,
  validationOptions: {
    someRandomThing: 'asdf',
    someOtherJunk: 123,
  },
  onSubmit: (values, { someRandomThing }) => {
    updateUser(values)
    doOtherThings({ someRandomThing })
  },
  defaultErrorMessage: `This won't have any effect in this case since we're using a custom validation function.`,
  forceShowOnSubmit: false,
})
```

#### Options

| Name                  | Type                | Description                                                                                                                                                                                              | Default Value                                      | Required? |
| --------------------- | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | --------- |
| `initialValues`       | { [string]: [any] } | An object with field names as keys and their initial values as values. Only field names in this object will be returned by the hook, so include the field here even if the initial value is `undefined`. |                                                    | Yes       |
| `validate`            | function            | A function that will receive two arguments: an object with field values by name and validationOptions. Should return an object with errors (or any falsy value to represent no error) by field name.     | Simple, truthy validation function                 | No        |
| `validationOptions`   | any                 | Allows any arbitrary second argument to be passed to `validate` and `onSubmit`. Used primarily for looking at values outside of your fields when validating.                                             |                                                    | No        |
| `onSubmit`            | function            | Called by the hook when `handleSubmit` is invoked and all fields are valid. Passed the same arguments as `validate`.                                                                                     |                                                    | No        |
| `defaultErrorMessage` | string              | The error message that will be set to a field by the default validation function.                                                                                                                        | `"Looks like that didn't work. Please try again."` | No        |
| `forceShowOnSubmit`   | boolean             | Causes touched to be set to true for all fields when `handleSubmit` is invoked.                                                                                                                          | `true`                                             | No        |

### Output

An object with two keys: `fields` and `handleSubmit`.

`fields` is an object that contains the following keys for each field you passed in:

- `value`: the value of the field
- `touched`: whether the field has been blurred
- `error`: any error message returned from the validate function for this field
- `onChange`: call this with either a value or an event to update the field's value
- `onBlur`: call this to set touched to `true` for the field

`handleSubmit` is a function that will call `onSubmit` (if it was passed). If forceShowOnSubmit is true, `touched` will be set to true on all fields when `handleSubmit` is invoked.

---
_Source: https://npm.io/package/use-validation · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
