Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

React hook to handle controlled form change and validation.

License

NotificationsYou must be signed in to change notification settings

knightburton/react-use-form

Repository files navigation

Development Workflownpmnpm

React hook to handle controlled form change and validation.

Getting started

Compatibility

Your project needs to useReact.js 16.8 or later.

Installation

$ npm i @knightburton/react-use-form

or

yarn add @knightburton/react-use-form

Usage

Here's an example of basic usage:

importReactfrom'react';importuseFormfrom'@knightburton/react-use-form';constApp=()=>{constonSubmit=data=>console.log(data);const{ fields, handleChange, handleSubmit}=useForm({schema:[{field:'text',value:''}],    onSubmit,});return(<formonSubmit={handleSubmit}><inputtype="text"id="text"name="text"value={fields.text.value}onChange={handleChange}/>{fields.text.error&&<p>{fields.text.error}</p>}<inputtype="submit"value="Submit"/></form>);};exportdefaultApp;

For more detailed example check theexample directory.

Output

The hook returns an object with the following props.

Prop nameTypeDescription
fieldsobjectGenerated fields state with values and errors.
handleChangefunctionThe function is used to update a value inside the fields state. It accepts an input change event.
handleSubmitfunctionThe function is used to submit the fields state for validation. It can accept an event, the behavior of that can be prevented with thepreventDefaultEventOnSubmit andstopPropagationEventOnSubmit option.
updateSchemafunctionThe function is used to submit a new or updated fields state.

Options

The hook behavior can be modified with the following props.

Prop nameTypeDefault ValueDescription
schemaobject[][]Defines the initial fields state and provides the validation rules for later. Check theschemaprop definitions
onSubmitfunctionundefinedFunction called when the validation was successful afterhandleSubmit triggered. The values fromfields state will be the first argument.
onErrorfunctionundefinedFunction called when the validation was unsuccessful afterhandleSubmit triggered. The validatedfields state will be the first argument.
resetOnSubmitbooleanfalseWhether the field values should be reset to the default value after successfulonSubmit or not.
preventDefaultEventOnSubmitbooleantrueWhether thehandleSubmit event default behavior should be prevented (if event provided) or not.
stopPropagationEventOnSubmitbooleantrueWhether thehandleSubmit event propagation should be prevented (if event provided) or not.

Schema Option

The option itself is anarray of objects and each object should look like this:

Prop nameTypeMandatoryDefault ValueDescription
fieldstringYes-Identifier of the field.
valuegenericYes-Defines the initial value of the field.
requiredboolean /Validator /functionNofalseDefines whether the field is required or not during the validation. It can be a special validator where theerror is optional and the fallback will be therequiredError or the default builtin error. It can be a function where you can decide whether the field should be required or not based on other field values or the actual field value.
requiredErrorfunction /stringNoThis field is required.Defines the returned error when a field marked as required. Check theerror definitions.
validatorsarrayNo[]Defines the validation rules. Check thedefinitions.

Validators

This is anarray of objects where each item defines rules and error messages:

Prop nameTypeMandatoryDescription
rulefunction /RegExpYesDefines the rule for field validation. It can be a function where the first arg is the corresponding field value and the second arg is the field values for complex rules. The function must returnboolean value.
errorfunction /stringYes (No, if used for required.)Defines the error message for invalid field. It can be a function where the first arg is the corresponding field value and the second arg is the field values for complex message. The function must returnstring value.

Development

Local development is broken into two parts (ideally using two terminal tabs).

First, run rollup to watch yoursrc/ module and automatically recompile it intodist/ whenever you make changes.

# Assume that you are in the project main folder$ npm i$ npm start

The second part will be running theexample/ create-react-app that's linked to the local version of your module.

# Assume that you are in the project main folder$cd example$ npm i$ npm start

Contributing

First off all, thanks for taking the time to contribute! 💪

Before any action, please visit theCode of Conduct andContributing guideline for more information.

License

react-use-form is Open Source software under the MIT license. Complete license and copyright information can be found within thelicense.


[8]ページ先頭

©2009-2025 Movatter.jp