0.6.0 • Published 4 years ago

react-data-input v0.6.0

Weekly downloads
3
License
MIT
Repository
github
Last release
4 years ago

A library to automatically bind React form elements to state attributes with automatic type conversion and validation. Give it a try.

import { Form, Input, TextArea } from 'react-data-input';

const state = { username: 'Foo', age: 20 };

function MyComponent(props) {
  return (
    <Form onSubmit={mySaveFunction} state={state}>
      <Input type="text" name="username" required maxLength="100" />
      <Input type="number" name="age" min="0" step="1" />
    </Form>
  );
});

Any user input is converted into the right type (number, date, boolean) and assigned to the corresponding attribute inside the state object. When submitted, the Form container validates all fields before triggering the onSubmit callback.

The following components are supported:

  • Form
  • Input (text, number, checkbox, radio, url, email, date, time)
  • TextArea
  • Select

Radio buttons require a RadioGroup ancestor to manage a mutually exclusive checked state.

Conversions

Each input field converts values automatically from string to the expected type:

  • text, url and email are validated for format and passed as is:
<Input type="email" name="email" />
<TextArea name="description" />

The native HTML element is used for data input, and the data is validated again using JavaScript before submission.

  • number is converted to a JavaScript with decimals according to the value of step (default is 1):
<Input type="number" name="age" />
<Input type="number" name="percentage" step="0.01" />
  • checkbox is transformed to a boolean:
<Input type="checkbox" name="subscribed" />
  • date and time are validated for format and min/max restrictions, then passed as strings with format yyyy-MM-dd and HH:mm respectively.
<Input type="date" name="birthdate" min="1900-01-01" max="2020-01-01" pattern="\d{4}-\d{2}-\d{2}"/>
<Input type="time" pattern="[0-9]{2}:[0-9]{2}">

Keep in mind that these will render the corresponding native HTML elements, which are supported on all major browsers except Safari on MacOS, where input[type=text] will be used instead. For this reason we recommend to set a pattern attribute like the example above. Even though the date picker doesn't use it, the text input fallback will.

These conversions are the default, but you can override the converter associated to any form field:

const AllowedValues = { one: instanceOne, two: instanceTwo };
const state = { defcon: AllowedValues.one }
const myConverter =

    // transform from String to Object
    toObject: function(value) {
      return AllowedValues[value] || AllowedValues.one;
    },

    // transform from object to String
    toString: function(value) {
      const key = Object.keys(AllowedValues).find((key) => AllowedValues[key] === value);
      return key || 'one';
    }

};

<Input type="text" name="defcon" converter={myConverter} state={state}/>

Validations

Before submitting the form, all user input is validated. The field validations are configured according to the following input atributes:

  • [required]
  • [pattern]
  • [min] and [max] for [type=number|date|time]
  • [type=email]
  • [type=url]

When the user submits a Form, the onSubmit callback will only be called if all validations pass. If there are errors an error message will be displayed instead, and focus will be transferred to the first field that didn't pass.

You can override the validation applied to a component, returning either a Promise or the validation result:

const validator = (value, props) => {
  return fetch('checkValueIsAvailable', {
    body: { username: value }
  });
}

<Form onSubmit={save} state={state}>
  <label htmlFor="username">Choose your username</label>
  <Input type="text" name="username" validator={validator} />
</Form>

The function should return undefined if the validation passes, or an error message otherwise.

Internationalization

To override the locale for validation messages, call Messages.set() once when initializing your application:

import { Messages } from 'react-data-input';

Messages.set({
    required: "Por favor, rellena este campo",
    min: "El valor debe ser mayor o igual que ${min}"
})

The full list of values validation messages is available in Messages.js.

Accessibility

Both input fields and alert messages will use the corresponding ARIA attributes (aria-invalid, aria-describedBy and role=alert) to be used by assistive technologies.

Play with the test suite

Feel free to play with our test suite:

# To run the test suite based on Mocha
npm run test
npm run coverage

# To fiddle with the browser and a sample form at
# http://localhost:8080/test-page/example.html
npm run dev
0.6.0

4 years ago

0.5.2

4 years ago

0.5.1

5 years ago

0.5.0

5 years ago

0.3.1

5 years ago

0.3.0

5 years ago

0.2.2

5 years ago

0.2.1

6 years ago

0.2.0

7 years ago

0.1.0

7 years ago

0.0.22

7 years ago

0.0.21

7 years ago

0.0.19

7 years ago

0.0.18

7 years ago

0.0.17

7 years ago

0.0.16

7 years ago

0.0.15

7 years ago

0.0.14

7 years ago

0.0.13

7 years ago

0.0.12

7 years ago

0.0.11

7 years ago

0.0.10

7 years ago

0.0.9

7 years ago

0.0.8

7 years ago

0.0.7

7 years ago

0.0.6

7 years ago

0.0.4

7 years ago

0.0.3

7 years ago

0.0.2

7 years ago

0.0.1

7 years ago