@rakered/forms
Tiny helper to help with form submissions

Usage
The most basic helper is getFormData, it takes either the event directly, or an HTML form element. What it returns, is a dictionary holding the values of the form.
import { getFormData } from '@rakered/forms';
const onSubmit = (event) => {
const data = getFormData(event);
// » { name: 'smeijer', password: { digest: 'd03…83e', algorithm: 'sha-256' } }
};
<form onSubmit={onSubmit}>
<input name="user" />
<input name="password" type="password" />
</form>;Because we often want to wrap submit handlers between event.preventDefault() and return false, there is a handleSubmit helper that does exactly that.
import { handleSubmit } from '@rakered/forms';
const onSubmit = handleSubmit((values) => {
// » { name: 'smeijer' }
});
<form onSubmit={onSubmit}>
<input name="user" />
</form>;Path expansions
Where applicable, input names will be expanded to object structures
<form onSubmit={onSubmit}>
<input name="user.name" value="Stephan Meijer" />
<input name="user.age" type="number" value="34" />
<input name="hobbies[]" value="chess" />
<input name="hobbies[]" value="art" />
</form>serializes to:
{
user: {
name: 'Stephan Meijer',
age: 34,
},
hobbies: ['chess', 'art'],
}Type Coercion
A number of specific input types, are coerced to the proper data type.
-
password { digest: String, algorithm: ‘sha-256’ } This one is important, so let’s start with that. Passwords are hashed using @rakered/hash, so you won’t be reading the password that the user entered. Please don’t try to work arround this. Instead, embrace it.
-
datetime-local Date The
datetime-localinput stores a full date, so the is converted to a proper Date. Other date-like fields, such asdate,time, orweekonly support partial dates, and are left alone. -
checkbox Boolean
-
number Number
-
range Number
Typescript
Both methods are typed and accept a generic to make the values a typed object. Together with the typecoercion, this can simplify form handling a lot.
interface User {
name: string;
age: number;
}
const signup = handleSubmit<User>((values) => {
// » { name: 'smeijer', age: 34 }
});
<form onSubmit={signup}>
<input name="user" />
<input name="age" type="number" />
</form>;