Skip to content

Commit 75f1a44

Browse files
authored
Merge pull request #163 from Jenesius/issue_149
Issue 149
2 parents d4d5977 + 8434ffd commit 75f1a44

File tree

8 files changed

+392
-86
lines changed

8 files changed

+392
-86
lines changed

docs/guide/working-with-values.md

Lines changed: 199 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1,91 +1,222 @@
1-
# Form Validation
1+
# Working with values
2+
This page contains all the methods and properties that you will need to work with the state of the form.
23

3-
For form validation, the **validate** method is used, which returns a boolean value - is
4-
whether the form is valid. In the process of executing this method, all child elements are checked for
5-
validity. They also call **validate** methods, if present. This is also the case for the following
6-
child elements, and so on deeper.
4+
## Set value {setValues}
75

8-
```vue{7-9}
9-
<template>
10-
<form-field name="age" :validation="ageValidation"/>
11-
</template>
12-
<script setup>
13-
import {Form, FormField} from "jenesius-vue-form";
6+
The main task of forms is to maintain the current state (value). To change it, use the **setValues** method:
7+
```ts
8+
form.setValues({
9+
name: "Jack",
10+
age: 24
11+
})
12+
form.values // { name: "Jack", age: 24 }
13+
```
14+
15+
### Options
16+
17+
#### values <Badge type="tip">Required</Badge>
18+
The values when will be set for the form.
19+
20+
#### options <Badge type="info">Optional</Badge>
21+
An optional parameter, an object with the following properties:
22+
23+
:::info_
24+
##### changed <Badge type="info">Optional</Badge>
25+
Boolean value whether the given values are changes. If *true* then values will be projected onto changes.
26+
27+
#### target <Badge type="info">Optional</Badge>
28+
The name of the target on which setValues was called. You can look at this property as if the method was called
29+
from the child element whose name was passed to *target*.
1430

15-
function ageValidation(x) {
16-
return x > 17 || 'So small'
17-
}
31+
#### clean <Badge type="info">Optional</Badge>
32+
Whether to completely overwrite the previous value. By default, *setValues* mixes in the value, but if set
33+
`clean: true`, the previous value will be completely overwritten by the new one.
34+
:::
1835

19-
form.setValues({ age: 17 });
20-
form.validate() // false
36+
### Examples of using
2137

22-
form.setValues({ age: 24 });
23-
form.validate() // true
24-
</script>
38+
#### Set value
39+
```ts
40+
form.setValues({
41+
username: "Jack"
42+
})
43+
form.values // { username: "Jack" }
44+
```
45+
46+
#### Set value with target parameter
47+
```ts
48+
form.setValues({
49+
city: "Emerald City"
50+
}, { target: "address" })
51+
form.values // { address: { city: "Emerald City" } }
2552
```
2653

27-
For field validation, FormField takes one required parameter:
54+
#### Using the clean parameter
55+
```ts
56+
// Values: { username: "Jenesius", age: 24 }
57+
form.setValues({ username: "Jenesius", age: 24 })
58+
59+
form.setValues({
60+
name: "Jask"
61+
}, { clean: true })
62+
form.values // { name: "Jack" }
63+
```
2864

29-
#### Validation <Badge type = "tip">Required</Badge>
30-
It has the following type:
65+
#### Using target and clean together
3166
```ts
32-
interface FormFieldProps {
33-
validation: FormFieldValidationCallback[] | FormFieldValidationCallback // [!code focus]
34-
}
67+
form.setValues({
68+
name: "Jack",
69+
address: {
70+
city: "Emerald City"
71+
}
72+
})
73+
74+
form.setValues({
75+
code: "00"
76+
}, { target: "address", clean: true })
77+
form.values // { name: "Jack", address: { code: "00" } }
3578
```
36-
As you can see from the specification, the field can accept both a single function and an array of functions. The function type is described below:
79+
80+
#### Mixing in the value
3781
```ts
38-
type FormFieldValidationCallback = (value: any) => true | string | boolean
82+
form.setValues({
83+
address: {
84+
city: "Emerald City"
85+
}
86+
})
87+
// { address: { city: "Emerald City" } }
88+
89+
form.setValues({
90+
address: {
91+
code: "00"
92+
}
93+
})
94+
form.values // { address: { city: "Emerald City", code: "00" } }
3995
```
4096

41-
- If the function returned *true* - the input field is valid, otherwise it is not.
42-
- If an array of functions is passed, then they will be run one after another and the field will be valid if all
43-
functions will return true.
97+
## Changing values
98+
As is already clear from **setValues**, if we pass `change: true`, then the work is done with the **changes** state
99+
forms. For convenient work, alias **change** was created, which automatically sets the changed parameter.
100+
```ts
101+
form.change(data) // form.setValues(data, { changed: true })
102+
```
44103

45-
## Validation Examples
104+
## Undo changes
105+
To undo changes (work with changes) use the *revert* method:
106+
```ts{5}
107+
form.setValues({username: "Jenesius", age: 24});
108+
form.change({age: 23, father: true});
109+
// Values: { username: "Jenesius", age: 23, father: true }
46110
47-
### Size limit
48-
```vue
49-
<template>
50-
<form-field name="token" :validation="validation"/>
51-
</template>
52-
<script setup>
53-
import {FormField, Form} from "jenesius-vue-form";
111+
form.revert();
112+
// Values: { username: "Jenesius", age: 24}
113+
```
54114

55-
const validation = [
56-
x => x.length > 5 || "That's too short. The minimum length is 5.",
57-
x => x.length < 25 || "Value length must be less than 25."
58-
]
59-
</script>
115+
## Clear values
116+
To completely clear the form, use the **cleanValues** method:
117+
```ts
118+
form.setValues({name: "Jack"})
119+
form.cleanValues(); // Values: {}
120+
```
121+
This method also accepts values that will be set instead of the current one:
122+
```ts
123+
form.setValues({name: "Jack"})
124+
form.cleanValues({age: 24}); // Values: { age: 24 }
60125
```
61-
### Checking the dependency of two fields
62126

63-
This example demonstrates how you can use field validation that depends on the value of another field. IN
64-
In this example, there are two rules:
127+
## Form Values (Values)
128+
From the previous examples, you can see that the final value of the form is in `form.values`:
129+
```ts
130+
form.setValues({age: 24});
131+
form.values // { age: 24 }
132+
```
65133

66-
- If the switch is set to true, then the admin rule is used for Login: admin login starts with
67-
$.
68-
- If the switch is off, then the user rule is used for Login: string length must be greater than 5.
69134

70-
```vue{3}
71-
<template>
72-
<form-field type="switch" name="isAdmin"/>
73-
<form-field name="login" :validation="validation"/>
74-
</template>
75-
<script setup>
76-
import {FormField, Form, ComputedValue} from "jenesius-vue-form";
135+
## Form changes (Changes)
136+
To get only the changes, you need to use `form.changes`:
137+
```ts{4}
138+
form.setValues({ name: "Jack" })
139+
form.change({ age: 24 })
140+
form.values; // { name: "Jack", name: 24 }
141+
form.changes; // { age: 24 }
142+
```
77143

144+
## Get value by name
145+
In some situations, there is a need to get the value of a field by name. For this case, you need to use
146+
namely the **getValueByName** method.
147+
148+
### Options
149+
150+
#### name <Badge type="info">Optional</Badge>
151+
The string name of the field to get the value for.
152+
153+
```ts{2}
154+
form.setValues({ login: "Jack" });
155+
form.getValueByName('login') // Jack
156+
```
157+
::: warning
158+
Getting a value by property name is erroneous:
159+
```ts
160+
form.values['login'] // Wrong
161+
form.getValueByName('login') // Correct
162+
```
163+
If we are talking about simple fields, this will work, but in the case of compound fields (address.country) this
164+
method will not be able to find the required field value.
165+
:::
166+
167+
## Accept changes
168+
To accept all changes or only for a specific field, use the **acceptChanges** method.
169+
The method clears changes (whole or single field) and sets the cleared value to values.
170+
171+
### Parameter
172+
173+
#### name <Badge type = "info">Optional</Badge>
174+
If not passed, all changes will be first projected onto values and then cleared. If the value
175+
passed it must be a string field name.
176+
177+
### Example
178+
179+
```ts
78180
const form = new Form();
79-
const isAdmin = ComputedValue(form, "isAdmin"); // For reactive communication
80-
const validation = [
81-
login => {
82-
if (isAdmin.value && !login.startsWith('$'))
83-
return 'Administrator name must start with $';
84-
if (!isAdmin.value && login.length < 5)
85-
return 'Username must be at least 5 characters long.'
86-
87-
return true;
88-
}
89-
]
90-
</script>
181+
form.change({ username: "Jack", age: 24, id: 1 })
182+
183+
form.acceptChanges('username');
184+
form.pureValues; // { username: "Jack" }
185+
form.changes // { age: 24, id: 1 }
186+
187+
form.acceptChanges();
188+
form.pureValues; // { username: "Jack", age: 24, id: 1 }
189+
form.changes; // {}
190+
```
191+
192+
## Clear field changes
193+
The **cleanChangesByField** method undoes the changes for the passed field. This function only works on the changes object and does not
194+
affects the values object. If the object's child property changes is an object, but the number
195+
child keys is 0, this property is completely removed from the changes object.
196+
197+
```ts
198+
form.setValues({age: 24})
199+
form.change({name: "Jack", age: 25}); // { name: "Jack", age: 25 }
200+
form.cleanChangesByField('name');
201+
// Changes: { name: "Jack" }
202+
// Values: { name: "Jack", age: 24 }
203+
```
204+
205+
## Check field for change
206+
The **checkFieldChange** method checks for changes to the passed field name. If the field has been changed
207+
will return true, false otherwise.
208+
```ts
209+
form.change({name: "Jack"});
210+
form.checkFieldChange('name') // true
211+
form.checkFieldChange('age') // false
212+
```
213+
214+
## Form Status (Changed)
215+
To understand that the form is in a changed state, you need to get the value of the **changed** property;
216+
```ts
217+
form.changed // false
218+
form.change({ name: "Jack" })
219+
form.changed // true
220+
form.revert();
221+
form.changed // false
91222
```

docs/ru/guide/working-with-values.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,31 @@ form.getValueByName('login') // Correct
164164
способ не сможет найти нужное значение поля.
165165
:::
166166

167+
## Принятие изменений
168+
Для того чтобы подтвердить все изменения или только для конкретного поля, воспользуйтесь методом **acceptChanges**.
169+
Метод очищает changes (целиком или единичное поле) и устанавливает очищенное значение в values.
170+
171+
### Параметра
172+
173+
#### name <Badge type = "info">Необязательное</Badge>
174+
Если не передано - все изменения будет сперва проецированы на values, а затем очищены. Если значение
175+
передаётся оно должно быть строковым названием поля.
176+
177+
### Пример
178+
179+
```ts
180+
const form = new Form();
181+
form.change({ username: "Jack", age: 24, id: 1 })
182+
183+
form.acceptChanges('username');
184+
form.pureValues; // { username: "Jack" }
185+
form.changes ; // { age: 24, id: 1 }
186+
187+
form.acceptChanges();
188+
form.pureValues; // { username: "Jack", age: 24, id: 1 }
189+
form.changes; // {}
190+
```
191+
167192
## Очистка изменений для поля
168193
Метод **cleanChangesByField** отменяет изменения для переданного поля. Данная функция работает только с объектом changes и не
169194
затрагивает объект values. Если в дочернее свойство объекта changes является объектом, но при этом количество

0 commit comments

Comments
 (0)