React forms made easy using an intuitive hooks-based API
yarn add use-simple-form
import { useForm } from 'use-simple-form';
function SignUp() {
const { setValue, getValue, submit } = useForm({ onSubmit: form => {/* Do stuff... */} });
return (
<>
<TextInput name="username" value={getValue('username')} onChange={setValue('username')} />
<TextInput name="password" value={getValue('password')} onChange={setValue('password')} />
<button label="Submit" onClick={submit} />
</>
);
}
Hook that accepts a form configuration object and returns methods used to control a form.
const form = useForm({
initialValues: { email: 'initial.value@email.com' },
onSubmit: formValues => {/* Custom logic... */},
validate: 'onSubmit', // Use array for multiple triggers: ['onSubmit', 'onChange'],
rules: {
oldPassword: rules.required(),
newPassword: [rules.match('password'), rules.required()] // Use an array to pass multiple rules
}
})
Rules are validation functions that can be applied at the field or form level.
Note: All pre-defined rules can have the default error message overridden using the final argument of the rule function.
import { rules } from 'use-simple-form';
This rule enforces that a field have a truthy value.
rules: {
myField: rules.required('myField requires a value!')
}
This rule will attempt to match the value of one field to another.
rules: {
password: rules.required(),
confirmPassword: rules.sameAs('password', 'Passwords must match!')
}
Attempts to match the input field value with either a pre-defined or given RegEx pattern.
Currently there are only 2 pre-defined RegEx patterns:
'email'
: Matches an email'password
: Matches a password with at least 1 uppercase, at least 1 lowercase, at least 1 number and at least 1 special character.
Check against a pre-defined pattern by passing the name:
rules.match('password');
Or pass a custom pattern:
rules: {
alphabet: rules.match(/^[A-Za-z]$/i, 'Not an alphabetical character!')
}
This rule checks that the input value should match an element of a given array.
rules: {
myField: rules.oneOf(['a', 'b', 'c'], 'Invalid character!')
}
This library includes some common rules that cover simple use cases. For more advanced use cases you may need to create your own, a rule function should follow the below signature:
String => ?String