A set of form hooks with validation for Q Blockchain frontend projects.
To install the library, run the following command:
yarn add @q-dev/form-hooks
or
npm install @q-dev/form-hooks
import { useForm, required } from '@q-dev/form-hooks';
const form = useForm({
initialValues: {
name: '',
email: '',
password: '',
},
validators: {
name: [],
email: [required],
password: [required],
},
onSubmit: (values) => {
console.log(values);
},
});
import { useForm, required } from '@q-dev/form-hooks';
const form = useForm({
initialValues: {
name: '',
email: '',
password: '',
},
validators: {
name: [],
email: [required],
password: [
required,
val => ({
isValid: !val || PASSWORD_REGEX.test(String(val)),
message: 'Invalid password',
})
],
},
onSubmit: (values) => {
console.log(values);
},
});
Translations can be provided with type
property from validator
object. Types for each validator can be found here.
import { useForm, required } from '@q-dev/form-hooks';
const form = useForm({
initialValues: { name: '' },
validators: { name: [] },
onSubmit: (values) => {
console.log(values);
}
});
const { t } = useTranslation();
const translateError = (type: string) => {
switch (type) {
case 'required':
return t('validation.required');
default:
return error;
}
};
import { useForm, required } from '@q-dev/form-hooks';
const form = useForm({
initialValues: { name: '' },
validators: { name: [] },
onSubmit: (values) => {
console.log(values);
}
});
return (
<form onSubmit={form.submit}>
<input
type="text"
name="name"
value={form.values.name}
onChange={e => form.fields.name.onChange(e.target.value)}
/>
{form.errors.name && <span>{form.errors.name}</span>}
{/* or with Q UI Kit input */}
{/* https://gitlab.com/q-dev/q-web-kit/-/blob/main/packages/ui-kit/src/components/Input/Input.tsx */}
<Input {...form.fields.name} />
<button type="submit">Submit</button>
</form>
);
We welcome contributions to the library. If you would like to submit a pull request, please make sure to follow our code style.
This project and everyone participating in it is governed by the Q Form Hooks Code of Conduct. By participating, you are expected to uphold this code.