Skip to content
This repository was archived by the owner on Jan 9, 2022. It is now read-only.

Commit 63d7460

Browse files
authored
feat: reset fields with specific values (#44)
* feat: reset fields with specific values * fix import * update readme * use block statements * Update README.md * update packages
1 parent 922af8f commit 63d7460

File tree

13 files changed

+845
-762
lines changed

13 files changed

+845
-762
lines changed

README.md

Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
[![npm](https://img.shields.io/npm/v/vue3-form-validation)](https://www.npmjs.com/package/vue3-form-validation)
44

5-
Opinionated Vue composition function for Form Validation.
5+
Vue composition function for Form Validation.
66

77
- :milky_way: **Written in TypeScript**
88
- :ocean: **Dynamic Form support**
@@ -34,12 +34,11 @@ const {
3434

3535
- `formData`
3636
- **Type** - `object`
37-
- **Required** - `true`
38-
- **Description** - The structure of your `formData`.
37+
- **Description** - The structure of your form data.
3938

40-
The `formData` object has a structure that is similar to any other object you would write for `v-model` data binding. The only difference being that together with every value you can provide rules to display validation errors.
39+
The form data object has a structure that is similar to any other object you would write for `v-model` data binding. The only difference being that together with every value you can provide rules to display validation errors.
4140

42-
Let's look at an example how the structure of some `formData` object can be converted to an object with the addition of rules:
41+
Let's look at an example how the structure of some form data object can be converted to an object with the addition of rules:
4342

4443
```ts
4544
const formData = {
@@ -67,7 +66,7 @@ const formDataWithRules = {
6766
};
6867
```
6968

70-
The `formData` object can contain arrays and can be deeply nested. At the leaf level, the object should contain Form Fields whose simplified type definition looks like the following:
69+
The form data object can contain arrays and can be deeply nested. At the leaf level, the object should contain fields whose simplified type definition looks like the following:
7170

7271
```ts
7372
type Field<T> = {
@@ -76,7 +75,7 @@ type Field<T> = {
7675
};
7776
```
7877

79-
To get better type inference while writing the `useValidation` function, it's recommended to define the structure of your `formData` upfront and pass it as the generic parameter `T`. The type for the example above is pretty straightforward:
78+
To get better type inference while writing the `useValidation` function, it's recommended to define the structure of your data upfront and pass it as the generic parameter `T`. The type for the example above is pretty straightforward:
8079

8180
```ts
8281
type FormData = {
@@ -92,15 +91,15 @@ const { ... } = useValidation<FormData>({ ... });
9291

9392
- `form`
9493
- **Type** - `object`
95-
- **Description** - Transformed `formData` object.
94+
- **Description** - Transformed form data object.
9695
- `submitting`
9796
- **Type** - `Ref<boolean>`
9897
- **Description** - `True` during validation after calling `validateFields`.
9998
- `errors`
10099
- **Type** - `ComputedRef<string[]>`
101100
- **Description** - Array of all current validation error messages.
102101

103-
`Form` is a reactive object with identical structure as the `formData` input.
102+
`Form` is a reactive object with identical structure as the form data input.
104103
Every object with a `$value` property will be converted to an object of the following form:
105104

106105
```ts
@@ -124,14 +123,14 @@ type Form = {
124123
```
125124

126125
As you may have noticed, all of the properties are prefixed with the `$` symbol, which is to distinguish them from other properties but also to avoid naming conflicts. Below is a
127-
description of all the fields an their use case:
126+
description of all the properties and their use case:
128127

129128
- `$uid`
130129
- **Type** - `number`
131-
- **Description** - Unique identifier of the Form Field. For dynamic Forms this can be used as the `key` attribute in `v-for`.
130+
- **Description** - Unique identifier of the field. For dynamic forms this can be used as the `key` attribute in `v-for`.
132131
- `$value`
133132
- **Type** - `T`
134-
- **Description** - The `modelValue` of the Form Field which is meant to be used together with `v-model`.
133+
- **Description** - The `modelValue` of the field, which is meant to be used together with `v-model`.
135134
- `$errors`
136135
- **Type** - `string[]`
137136
- **Description** - Array of validation error messages.
@@ -140,25 +139,27 @@ description of all the fields an their use case:
140139
- **Description** - `True` while at least one rule is validating.
141140
- `$onBlur`
142141
- **Type** - `function`
143-
- **Description** - Function which will mark this Form Field as touched. When a Field has been touched it will validate all it's rules after every input. Before it will not do any validation.
142+
- **Description** - Function which will mark this field as touched. When a field has been touched, it will validate all it's rules after every input. Before it will not do any validation.
144143

145144
### `useValidation` exposes the following methods:
146145

147146
- `validateFields() -> Promise`
148-
- **Description** - Validate all Fields.
149-
- **Returns** - A `Promise` which will reject if there are validation errors, and resolve with the `formData` otherwise.
150-
- `resetFields() -> void`
151-
- **Description** - Reset all Fields to their original values.
147+
- **Description** - Validate all fields.
148+
- **Returns** - A `Promise` which will reject if there are validation errors, and resolve with the form data otherwise.
149+
- `resetFields(formData?: object) -> void`
150+
- **Description** - Reset all fields to their original value, or pass an object to set specific values. Check out the [Sandbox](https://codesandbox.io/s/vue-3-form-validation-demo-7mp4z?file=/src/views/LoginForm.vue) for usage examples.
151+
- **Parameters**
152+
- `formData?` - Values to use.
152153
- `add(pathToArray: (string | number)[], value: any) -> void`
153-
- **Description** - Utility function for writing dynamic Forms.
154+
- **Description** - Utility function for writing dynamic forms.
154155
- **Parameters**
155-
- `pathToArray` - Tuple representing the path to an array in the `formData`.
156+
- `pathToArray` - Tuple representing the path to an array in the form data.
156157
- `value` - The value that will be pushed to the array at the given path.
157158
- `remove(pathToArray: (string | number)[], index: number) -> void`
158-
- **Description** - Utility function for writing dynamic Forms.
159+
- **Description** - Utility function for writing dynamic forms.
159160
- **Parameters**
160-
- `pathToArray` - Tuple representing the path to an array in the `formData`.
161-
- `index` - Array index that will be remove.
161+
- `pathToArray` - Tuple representing the path to an array in the form data.
162+
- `index` - Array index which will be remove.
162163

163164
## Writing Rules
164165

@@ -211,7 +212,7 @@ const isNameTaken = name =>
211212
## Contributing
212213

213214
If you find problems or if you have use cases that you think are not easy to achieve with the current API, please let me know :+1:
214-
Feel free to write an issue or open a pull request, for more information about the project checkout the
215+
Feel free to write an issue or open a pull request, for more information about the project check out the
215216
[contributing guideline](https://github.com/JensD98/vue3-form-validation/blob/master/.github/contributing.md).
216217

217218
## License

main/Form.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { computed, reactive, ref, unref } from 'vue';
2-
import { SimpleRule, Rule } from './composable/useValidation';
2+
import { SimpleRule, Rule } from './composition/useValidation';
33
import FormField from './FormField';
44
import { PromiseCancel, tryGet, trySet } from './utils';
55

@@ -101,9 +101,9 @@ export default class Form {
101101
});
102102
}
103103

104-
resetFields() {
104+
resetFields(toDefaultValues = true) {
105105
for (const { formField } of this.simpleValidators.values()) {
106-
formField.reset();
106+
formField.reset(toDefaultValues);
107107
}
108108
}
109109

@@ -121,9 +121,9 @@ export default class Form {
121121
}
122122
}
123123

124-
const settledResult = await Promise.allSettled(promises);
124+
const settledResults = await Promise.allSettled(promises);
125125

126-
for (const result of settledResult) {
126+
for (const result of settledResults) {
127127
if (result.status === 'rejected') {
128128
return true;
129129
}

main/FormField.ts

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
import { computed, isRef, reactive, ref } from 'vue';
2-
import { Rule } from './composable/useValidation';
2+
import { Rule } from './composition/useValidation';
33

44
const notNull = <T>(value: T | null): value is T => value !== null;
55

66
export default class FormField {
7-
private errors: (string | null)[];
8-
9-
rulesValidating = ref(0);
107
modelValue: ReturnType<typeof ref> | ReturnType<typeof reactive>;
11-
private initialModelValue: unknown;
128
touched = false;
9+
rulesValidating = ref(0);
10+
11+
private errors: (string | null)[];
12+
private initialModelValue: unknown;
1313

1414
constructor(rules: Rule[], modelValue: unknown) {
1515
this.errors = reactive(rules.map(() => null));
@@ -42,16 +42,18 @@ export default class FormField {
4242
return computed(() => this.rulesValidating.value > 0);
4343
}
4444

45-
reset() {
45+
reset(toDefaultValues: boolean) {
4646
this.touched = false;
4747

48-
if (isRef(this.modelValue)) {
49-
this.modelValue.value = this.initialModelValue;
50-
} else {
51-
Object.assign(this.modelValue, this.initialModelValue);
52-
this.initialModelValue = JSON.parse(
53-
JSON.stringify(this.initialModelValue)
54-
);
48+
if (toDefaultValues) {
49+
if (isRef(this.modelValue)) {
50+
this.modelValue.value = this.initialModelValue;
51+
} else {
52+
Object.assign(this.modelValue, this.initialModelValue);
53+
this.initialModelValue = JSON.parse(
54+
JSON.stringify(this.initialModelValue)
55+
);
56+
}
5557
}
5658

5759
Object.assign(

0 commit comments

Comments
 (0)