UNPKG

2.58 kBMarkdownView Raw
1
2# form
3
4[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://github.com/feross/standard)
5
6vdux form component
7
8## Installation
9
10 $ npm install vdux-form
11
12## Usage
13
14## API - props
15
16 * `onSubmit` - Handles a form submission. Receives the contents of the form, serialized to JSON, and casted by `cast` (if specified).
17 * `validate` - Validate the JSON contents of the form. Blocks `onSubmit` if not valid. Refer to the validation section for more details.
18 * `cast` - Before being validated you can transform the model with this. It should accept a model and return a new model.
19 * `loading` - Whether or not the form is currently loading. If `true`, submits will be disabled. Defaults to false.
20 * `transformError` - Transform an error response from your `onSubmit` function into a form that is consumable by `vdux-form`. A default can be specified using `setTransformError`.
21 * `onSuccess` - Run if `onSubmit` succeeds; receives the result as its first argument
22 * `onFailure` - Run if `onSubmit` throws an error; receives the error as its first argument
23
24## Validation
25
26Your `validate` function should accept a model and return an object of the form:
27
28`{valid: Boolean, errors: [Errors]}`
29
30If `valid` is `false`, `errors` should include a list of invalid fields. Each `error` entry should have the form:
31
32`{field, message}`
33
34Where `field` is the `name` attribute of the form field that the `message` applies to. Your `message` will then be set on the appropriate field using [setCustomValidity](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/setCustomValidity). This will trigger an [invalid](https://developer.mozilla.org/en-US/docs/Web/Events/invalid) event on that form field, which you can capture on the input.
35
36
37### Example
38
39```javascript
40import Form from 'vdux-form'
41
42function render () {
43 return (
44 <Form validate={validate}>
45 <input name='username' onInvalid={e => setError(e.target.validationMessage)} />
46 {
47 error && <span class='error'>{error}</span>
48 }
49 </Form>
50 )
51}
52
53function validate ({username}) {
54 if (username.length < 3) {
55 return {
56 valid: false,
57 errors: [{field: 'username', message: 'Username must be at least 3 characters long'}]
58 }
59 }
60
61 return {
62 valid: true
63 }
64}
65```
66
67### Error handling
68
69You can specify a default *transform* for your errors like this:
70
71```javascript
72import Form from 'vdux-form'
73
74Form.setTransformError(err => ({
75 if (err.status === 400) {
76 return err.errors
77 }
78}))
79```
80
81## License
82
83MIT