mobx-valite-form-store
TypeScript icon, indicating that this package has built-in type declarations

0.1.3 • Public • Published

MobX valite form Store

Build Status

A MobX form store using valite as validator.

Installation

This module is published under NPM Registry, so you can install using NPM, Yarn and other package managers.

npm install --save mobx-valite-form-store

# Use the command below if you're using Yarn.
yarn add mobx-valite-form-store

Usage

This module provides a store class to handle form states, validators & their error states.

import React, { Component } from 'react';
import { observer } from 'mobx-react';
import { observable } from 'mobx';
import FormStore from 'mobx-valite-form';

// An validator schema for entries object.
const validators = {
  name: [
    (name) => (typeof name === 'string' && !!name.trim()) || 'Name is a required entry.',
    (name) => (name.length > 2 && name.length < 30) || 'Name should have between 2 and 30 chars.'
  ]
};

@observer
export default class Form extends Component {
  @observable store = new FormStore({ name: '' }, validators);

  onSubmit = async () => {
    await this.store.validateEntries();

    if (!this.store.isValid)
      return;
    this.props.onSave(this.store.entries);
  };

  render () {
    return (
      <form>
        <input
          value={ this.store.entries.name }
          onChange={ (e) => this.store.setEntry('name', e.target.value) }
        />

        { this.store.errors.name && <span>{ this.store.errors.name }</span> }
      </form>
    );
  }
}

License

Released under MIT license.

Package Sidebar

Install

npm i mobx-valite-form-store

Weekly Downloads

0

Version

0.1.3

License

MIT

Unpacked Size

30.9 kB

Total Files

7

Last publish

Collaborators

  • vitorluizc