Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: useForm Field types #2996

Merged
merged 2 commits into from
Oct 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions docs/content/api/use-form.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ export default {
};
```

The `useForm` composable has very powerful type information and can be fully typed, for more information check the [useForm typing tutorial](/tutorials/use-form-types)

## API Reference

The full signature of the `useForm` function looks like this:
Expand Down Expand Up @@ -156,23 +158,26 @@ values.value; // { email: '[email protected]', .... }

<code-title level="4">

`setFieldError: (field: string, message: string) => void`
`setFieldError: (field: string, message: string | undefined) => void`

</code-title>

Sets a field's error message, useful for setting messages form an API or that are not available as a validation rule.
Sets a field's error message, useful for setting messages form an API or that are not available as a validation rule. Setting the message to `undefined` or an empty string clears the errors and marks the field as valid.

```js
const { setFieldError } = useForm();

setFieldError('email', 'this email is already taken');

// Mark field as valid
setFieldError('email', undefined);
```

If you try to set an error for field doesn't exist, it will not affect the form's overall validity and will be ignored.

<code-title level="4">

`setErrors: (fields: Record<string, string>) => void`
`setErrors: (fields: Record<string, string | undefined>) => void`

</code-title>

Expand All @@ -184,9 +189,16 @@ const { setErrors } = useForm();
setErrors({
email: 'this email is already taken',
password: 'someone already has this password 🤪',
firstName: undefined, // clears errors and marks the field as valid
});
```

<doc-tip>

Any missing fields you didn't pass to `setErrors` will be unaffected and their state will not change

</doc-tip>

<code-title level="4">

`setFieldValue: (field: string, value: any) => void`
Expand Down
73 changes: 73 additions & 0 deletions docs/content/guide/use-form-types.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
---
title: useForm() Field Types
description: Using field types with useForm
order: 7
---

# useForm() Field Types

The `useForm` function exposed by vee-validate has field typing capabilities if you need it, getting type information for your fields and their values can be very powerful when building complex forms.

By unlocking the field type you automatically get more strict information for the various properties/methods exposed by `useForm` like `setErrors` and `setTouched`. For more information about these properties/methods go to the [`useForm()` API reference](/api/use-form).

## Unlocking Field Types

There are two ways you can get the advanced typing information for your fields, the first is to provide a generic type to `useForm`.

```ts
import { useForm } from 'vee-validate';

interface LoginForm {
email: string;
password: string;
}

// in your setup
const { errors } = useForm<LoginForm>();
```

```ts
import { useForm } from 'vee-validate';

interface LoginForm {
email: string;
password: string;
}

// in your setup
const { errors, setErrors, setFieldValue } = useForm<LoginForm>();

errors.value; // typed as { email?: string; password?: string }

setErrors({
email: 'This field is invalid', // auto-complete for `email` and `password`
});

setFieldValue('email', '[email protected]'); // auto-complete for the field name and its value type
```

For example if you were to do this in the previous example:

```ts
setFieldValue('age', 5); // ⛔️ TypeScript error
setFieldValue('email', 5); // ⛔️ TypeScript error
```

It will error out because `age` is not defined in the `LoginForm` type you defined. The second line errors out because the `email` field is typed as a `string`.

## With Initial Values

You can also unlock the same capabilities for simpler fields by providing an `initialValues` property to `useForm`:

```typescript
import { useForm } from 'vee-validate';

const { errors, setErrors, setFieldValue } = useForm({
initialValues: {
email: '',
password: '',
},
});
```

`useForm` will automatically pick up the type of `initialValues` and use it for the field types.
36 changes: 21 additions & 15 deletions packages/core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,24 +30,30 @@ export type SubmitEvent = Event & { target: HTMLFormElement };

export type GenericValidateFunction = (value: any) => boolean | string | Promise<boolean | string>;

export interface FormContext {
export interface FormContext<TValues extends Record<string, any> = Record<string, any>> {
register(field: any): void;
unregister(field: any): void;
values: Record<string, any>;
fields: ComputedRef<Record<string, any>>;
schema?: Record<string, GenericValidateFunction | string | Record<string, any>> | ObjectSchema;
validateSchema?: (shouldMutate?: boolean) => Promise<Record<string, ValidationResult>>;
setFieldValue: (path: string, value: any) => void;
setFieldError: (field: string, message: string) => void;
setErrors: (fields: Record<string, string>) => void;
setValues: (fields: Record<string, any>) => void;
setFieldTouched: (field: string, isTouched: boolean) => void;
setTouched: (fields: Record<string, boolean>) => void;
setFieldDirty: (field: string, isDirty: boolean) => void;
setDirty: (fields: Record<string, boolean>) => void;
values: TValues;
fields: ComputedRef<Record<keyof TValues, any>>;
schema?: Record<keyof TValues, GenericValidateFunction | string | Record<string, any>> | ObjectSchema<TValues>;
validateSchema?: (shouldMutate?: boolean) => Promise<Record<keyof TValues, ValidationResult>>;
setFieldValue<T extends keyof TValues>(field: T, value: TValues[T]): void;
setFieldError: (field: keyof TValues, message: string | undefined) => void;
setErrors: (fields: Partial<Record<keyof TValues, string | undefined>>) => void;
setValues<T extends keyof TValues>(fields: Partial<Record<T, TValues[T]>>): void;
setFieldTouched: (field: keyof TValues, isTouched: boolean) => void;
setTouched: (fields: Partial<Record<keyof TValues, boolean>>) => void;
setFieldDirty: (field: keyof TValues, isDirty: boolean) => void;
setDirty: (fields: Partial<Record<keyof TValues, boolean>>) => void;
reset: () => void;
}

type SubmissionContext = { evt: SubmitEvent; form: FormContext };
type SubmissionContext<TValues extends Record<string, any> = Record<string, any>> = {
evt: SubmitEvent;
form: FormContext<TValues>;
};

export type SubmissionHandler = (values: Record<string, any>, ctx: SubmissionContext) => any;
export type SubmissionHandler<TValues extends Record<string, any> = Record<string, any>> = (
values: TValues,
ctx: SubmissionContext<TValues>
) => any;
Loading