masinton-form
v1.0.5
Published
A lightweight React hook for managing form state and validation. Each field is modeled as a `{ value, error, errorMessage }` object, and validation rules are simple `RegExp` tests.
Readme
Masinton Form
A lightweight React hook for managing form state and validation. Each field is modeled as a { value, error, errorMessage } object, and validation rules are simple RegExp tests.
Installation
npm install masinton-form
# or
yarn add masinton-formPeer dependencies: react@^18 and react-dom@^18.
Usage
import useMasintonForm, { MasintonForm, MasintonValidation } from 'masinton-form';
const formData: MasintonForm = {
username: { value: '', error: false, errorMessage: '' },
password: { value: '', error: false, errorMessage: '' },
};
const validation: MasintonValidation = {
username: [{ rule: /\S/, errorMessage: 'Username tidak boleh kosong' }],
password: [{ rule: /\S/, errorMessage: 'Password tidak boleh kosong' }],
};
const LoginForm = () => {
const { masintonForm, masintonChange, masintonValidation, masintonSubmit } =
useMasintonForm(formData, validation);
const { username, password } = masintonForm;
const handleSubmit = () => {
if (masintonValidation()) {
console.log(masintonSubmit());
}
};
return (
<>
<input
value={username.value}
onChange={(e) => masintonChange('username', e.target.value)}
/>
<div>{username.errorMessage}</div>
<input
type="password"
value={password.value}
onChange={(e) => masintonChange('password', e.target.value)}
/>
<div>{password.errorMessage}</div>
<button onClick={handleSubmit}>Submit</button>
</>
);
};A runnable example lives in example/index.tsx.
API
useMasintonForm(initialForm, validation?) returns:
| Property | Description |
| --- | --- |
| masintonForm | Current form state — { [field]: { value, error, errorMessage } }. |
| masintonWatch | { edited: boolean } — true when the form differs from the initial state. |
| masintonChange(key, value) | Update a single field's value. |
| masintonMultiChange(data) | Update multiple field values at once. |
| masintonMagic(data) | Replace values for the listed keys and reset edited (treats them as the new baseline). |
| masintonReplace(formData) | Replace the entire form with a new initial state. |
| masintonReset() | Reset the form back to the initial state. |
| masintonSubmit() | Returns a plain object of { [field]: value } for submission. |
| masintonValidation(options?) | Run validation rules. Returns true when all fields pass. Pass { ignoreValidation: string[] } to skip specific fields. |
Types
type MasintonField = { value: any; error: boolean; errorMessage: string };
type MasintonForm = { [key: string]: MasintonField };
type MasintonValidationRule = { rule: RegExp; errorMessage: string };
type MasintonValidation = { [key: string]: MasintonValidationRule[] };
type MasintonValidationOptions = { ignoreValidation?: string[] };License
MIT
