项目作者: VitorLuizC

项目描述 :
A MobX form store using `valite` as validator.
高级语言: JavaScript
项目地址: git://github.com/VitorLuizC/mobx-valite-form-store.git
创建时间: 2018-06-14T20:15:45Z
项目社区:https://github.com/VitorLuizC/mobx-valite-form-store

开源协议:MIT License

下载


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.

  1. npm install --save mobx-valite-form-store
  2. # Use the command below if you're using Yarn.
  3. yarn add mobx-valite-form-store

Usage

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

  1. import React, { Component } from 'react';
  2. import { observer } from 'mobx-react';
  3. import { observable } from 'mobx';
  4. import FormStore from 'mobx-valite-form';
  5. // An validator schema for entries object.
  6. const validators = {
  7. name: [
  8. (name) => (typeof name === 'string' && !!name.trim()) || 'Name is a required entry.',
  9. (name) => (name.length > 2 && name.length < 30) || 'Name should have between 2 and 30 chars.'
  10. ]
  11. };
  12. @observer
  13. export default class Form extends Component {
  14. @observable store = new FormStore({ name: '' }, validators);
  15. onSubmit = async () => {
  16. await this.store.validateEntries();
  17. if (!this.store.isValid)
  18. return;
  19. this.props.onSave(this.store.entries);
  20. };
  21. render () {
  22. return (
  23. <form>
  24. <input
  25. value={ this.store.entries.name }
  26. onChange={ (e) => this.store.setEntry('name', e.target.value) }
  27. />
  28. { this.store.errors.name && <span>{ this.store.errors.name }</span> }
  29. </form>
  30. );
  31. }
  32. }

License

Released under MIT license.