0.0.3 • Published 7 months ago

@su-hooks/use-form v0.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
7 months ago

@su-hooks/use-form

Custom React hook to use form with input validator

Usage

import useForm, { inputProps } from '@su-hooks/use-form';

export default function App() {
	const inputs: inputProps = {
		email: {
			value: initialValue,
			validator: (value) => value.indexOf('@') > -1,
		},
		password: { value: initialValue, validator: (value) => value.length > 7 },
	};

	const submitHandler = () => {
		// do something...
	};

	const { form, handleChange, handleSubmit, isFormValid } = useForm({
		inputs,
		submitHandler,
	});

	return (
		<form onSubmit={handleSubmit}>
			<input
				type='email'
				name='email'
				value={form.email.value}
				onChange={handleChange}
				required
			/>
			<InputField
				type='password'
				name='password'
				value={form.password.value}
				onChange={handleChange}
				required
			/>
			<button disabled={!isFormValid}>Submit</button>
		</form>
	);
}

Properties

NameTypeRequiredDefault
inputsinputPropsnull
submitHandlerFunctionnull
  • inputs

    • key: key has to be same with input's name. If they are different, never change input state.
    • value: initial input value.
    • validator: validator function is an optional property. If it is null, that input's validation is always true.
    type validator = (value: string) => boolean;
    
    interface inputProps {
    	[key: string]: { value: string; validator?: validator };
    }
  • submitHandler: When submit event is fired, this function will be executed.

Returns

NameTypeDescription
formObjectinput's information(value, validation)
handleChangeChangeEventinput change event
handleSubmitSubmitEventform submit event
isFormValidBooleanform validation
0.0.3

7 months ago

0.0.2

7 months ago

0.0.1

8 months ago