react-hooks-yup-form
v0.1.5
Published
React simple form on hooks, makes use of yup validation
Downloads
288
Maintainers
Readme
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 = values => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("submitted:", values);
resolve("done!");
}, 1000);
});
};
function SimpleForm() {
const [submitOn, setSubmitOn] = useState(true);
return (
<Form onSubmit={onSubmit}>
<fieldset>
<Field
name="userName"
label="*User name"
preserveValuesOnReset={true} // This field doesnt clear on submit
validate={value => (value ? "should be empty" : null)} // plain on-field validation
/>
<Field
name="url"
label="*Url"
placeholder="https://some.url.com"
yupSchema={yup
.string()
.url("Must be URL")
.required("Required")} // yup on-field validation
/>
<Field
name="fruit"
label="*Select a fruit"
component={Dropdown}
placeholder="Choose your favorite fruit"
validate={value => (value ? "should be empty" : null)} // plain on-field validation
options={[
{ label: "Grapefruit", value: "Grapefruit" },
{ label: "Lime", value: "Lime" }
]}
/>
<Submit disableIfInvalid={!submitOn}> // 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';
function DynamicForm() {
const [fields, setFields] = useState([
{
name: "first",
label: "First field",
value: "Initial field value",
validate: value => (value ? "should be empty" : null) // plain on-field validation
},
{
name: "second",
label: "Second field",
component: Input // component: Input might be not set directly as it is a default input
},
{
name: "third",
validate: value => (!value ? "required" : null),
component: Input, // not required, the Input is a default component used by form
preserveValuesOnReset: true // This field doesn't clear on submit
},
{
name: "select",
component: Dropdown,
placeholder: "Make your choice",
validate: value => (!value ? "required" : null),
options: [
{ value: "grapefruit", label: "Grapefruit" },
{ value: "lime", label: "Lime" },
{ value: "coconut", label: "Coconut" },
{ value: "mango", label: "Mango" }
]
},
{ name: "dt", type: "date" }
]);
return (
<>
<button
onClick={function RemoveField() {
setFields(fields.slice(0, fields.length - 1));
}}
>
Delete a field, then only rest of the fields will be submitted
</button>
<Form onSubmit={onSubmit}>
<fieldset>
{fields.map(({ children, ...fieldProps }) => (
<Field {...fieldProps} key={fieldProps.name} />
))}
<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.object().shape({
userNick: yup.string().required("Required"),
user: yup.object().shape({
name: yup.string().required("Required"),
password: yup.string().required("Required")
})
});
/*
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.
*/
function NestedForm() {
const [submitOn, setSubmitOn] = useState(true);
return (
<Form onSubmit={onSubmit} yupSchema={ValidationSchema}>
<fieldset>
<Field name="userNick" />
<Field name="user.name" label="*Nested field name: user.name" />
<Field name="user.password" type="password" />
<Submit>Submit</Submit>
</fieldset>
</Form>
);
}
The form will submit user data as a nested object:
userNick: 'something',
user: {
name: 'some-name',
password: 'pass'
}
}