1.0.1 • Published 3 years ago

json-msg-react v1.0.1

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

NPM JavaScript Style Guide

This might be similar to Formik but in a hook form , and this is also use json-msg as a validator. Json-msg is a lightweight alternative for yup and joi or any other schema validator.

Prerequisite

  • Basic knowledge of json-msg for building schema

Check json-msg documentation here

Install

npm install json-msg-react

or

yarn add json-msg-react

Usage

import React from "react";
import jm, { useForm } from "json-msg-react";

const schema = {
  username: jm.str({ min: 5 }),
  password: jm.str({ min: 8, max: 40 }),
  pin: jm.num({ digit: 4 }),
};
const initialData = {
  username: "",
  password: "",
  pin: 0,
};
const Example = () => {
  const { handleChange, handleSubmit, errors } = useForm(initialData, schema);

  function submit(data) {
    console.log(data);
  }
  return (
    <>
      <form onSubmit={handleSubmit(submit)}>
        <input name="username" onChange={handleChange} />
        {errors.username && <p> {errors.username} </p>}
        <input name="password" type="password" onChange={handleChange} />
        {errors.username && <p> {errors.username} </p>}
        <input name="pin" type="number" onChange={handleChange} />
        {errors.password && <p> {errors.password} </p>}
      </form>
    </>
  );
};

API

useForm(initialData,schema, option)


  • initialData:? Object
  • schema:? Object
optiontypedefaultdescription
showAllErrorsbooleanfalseShow all the errors in array form
trimbooleanfalseTrim all the string in the data
validateOnChangebooleantrueValidate on change the data
validateOnMountbooleanfalseValidate the data on mount