npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mobx-form

v13.3.6

Published

A simple form helper for mobx

Downloads

1,599

Readme

Mobx-Form

Simple helper for state management

TODO:

  • Add more examples
  • Add more unit tests
  • Add better documentation

Install

npm i --save mobx mobx-form

Usage

import { createModel } from 'mobx-form';

const model = createModel( {
  // the field descriptor
  // when calling model.validate(); all the validators are executed in parallel
  fieldName1: {
    // whether validation will happen automatically after first update
    autoValidate: true,
    // whether validation should wait until the field is blurred at least once
    // (meaning the blur event happened at least once in that field).
    //
    // This requires that the component calls `markBlurredAndValidate()` after
    // the blur even is raised on the field
    waitForBlur: false,
    // Very useful flag to just make a field required or not without requiring a validator
    // the `required` property can be:
    // - a boolean, in which case the error message shown will be `Required`
    // - a `string` in which case the string message will be used as the message to show when the field has no value
    required: 'This field is required',
    // optional, default error message is the validaor function return just true/false
    errorMessage:
    // optional, if `required` is defined. Required if not
    // the validation function it receive the current field and allFields for
    // validations that need to take in consideration more than one in conjuction
    //
    // - if validation passes function must return true.
    // - if validation does not pass the function should:
    //   - return false (default errorMessage specified in the validator will be used)
    //   - throw an error (error.message is going to be used as the errorMessage)
    //   - reject or return an object with an error field. like:
    //     ```
    //     return { error: 'some error' };
    //     return Promise.reject({ error: 'some error' }); // although this should be considered deprecated
    //     ```.
    validator = (field, allFields, model) => {
      // do validation
      // return true/false
      // throw new Error('some error');
      // return { error: 'some error '};
    }
  }
})

performValidation = async () => {
  // To call all validators
  await model.validate();

  // To check if valid (after awaiting the validate call)
  if (model.valid) {
    // get the serialized data
    // { fieldName: 'value set' }
    const obj = model.serializedData;

    // do something with the serializedData
    await xhr('/some/endpoint', { method: 'post', payload: obj });
  };
};


// to update values in the form.
model.updateFrom({ fieldName1: 'new value' }, /* reset = true */); // by default setting values using this method
                                                                   // will reset the interacted flag on the Field
                                                                   // and reset the validation error

Example:

import trim from 'jq-trim';
import { createModel } from 'mobx-form';

const model = createModel({
  descriptors: {
    name: {
      required: 'Name is required',
    },
    // validator for email
    email: {
      // validator function
      async validator(field) {
        const email = trim(field.value);
        // super simple and naive email validation
        if (!email || !(email.indexOf('@') > 0)) {
          throw new Error('Please provide an error message');
        }
      },
    },
    // validator for password
    password: {
      // validator function
      async validator(field) {
        if (!trim(field.value)) {
          throw new Error('Please provide your password');
        }
      },
    },
  },
  initialState: {
    email: '',
    password: '',
  },
});

const main = async () => {
  await model.validate();

  console.log('>>>> model.valid', model.valid);
  console.log('>>>> model.summary', model.summary);
  console.log('>>>> model.requiredFields', model.requiredFields);

  // >>>> model.valid false
  // >>>> model.summary [ 'Name is required',
  //   'Please provide an error message',
  //   'Please provide your password' ]
  // >>>> model.requiredFields [ 'name' ]
};

main().catch(err => console.error('>>> error', err));