React hooks form with yup validation
This form combines bits of Formik api with the author's personal approach on how to make it more easy in use and more dynamic in the same time.
The react hooks system was applied so the least compliant react version is 16.8.
The form is fast and lightweight, easy to use (see /examples).
The form could make use of plain validation functions as well as yup validation schema on both: form and field levels.
Install
npm i react-hooks-yup-form
or
yarn add react-hooks-yup-form
Run examples
yarn start
or
npm start
Simple form example with field-level validation
import Dropdown Submit Field Form from 'react-hooks-yup-form';import * as yup from 'yup'; const onSubmit = { return resolve reject ; ;}; { const submitOn setSubmitOn = ; return <Form => <fieldset> <Field ="userName" ="*User name" = // = // /> <Field ="url" ="*Url" ="https://some.url.com" = // /> <Field ="fruit" ="*Select a fruit" = ="Choose your favorite fruit" = // = /> <Submit => // Disable submit button while the form is invalid Submit </Submit> </fieldset> </Form> ;}
Dynamic form - maintains, submits and validates only actual list of fields
import Dropdown Submit Field Form from 'react-hooks-yup-form'; { const fields setFields = ; return <> <button = > Delete a field then only rest of the fields will be submitted </button> <Form => <fieldset> fields <Submit>Submit</Submit> </fieldset> </Form> </> ;}
Form with nested fields and field-level validation
import * as yup from 'yup';import Dropdown Submit Field Form from 'react-hooks-yup-form'; const ValidationSchema = yup;/*If you prefer use plain validation rather then yupSchema, make sure it returns results in the following format: {fild_name1: error_message, fild_name2: error_message2, ...} or falsy. Use "validate" prop to provide plain validation not "yupSchema".If you have set up both the yupSchema will win. */ { const submitOn setSubmitOn = ; return <Form = => <fieldset> <Field ="userNick" /> <Field ="user.name" ="*Nested field name: user.name" /> <Field ="user.password" ="password" /> <Submit>Submit</Submit> </fieldset> </Form> ;}
The form will submit user data as a nested object:
userNick: 'something',user: { name: 'some-name', password: 'pass' }}