Skip to content

Commit b0e834c

Browse files
committed
add state, on-change, validation, form functions
1 parent 19c370d commit b0e834c

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

src/js/model.js

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import onChange from "on-change";
2+
import * as yup from 'yup';
3+
4+
const object = {
5+
inputValue: '',
6+
rssFeed: [],
7+
errors: null
8+
};
9+
10+
const state = onChange(object, (path, value) => {
11+
console.log(`состояние изменено: ${path}`, value);
12+
});
13+
14+
const schema = yup
15+
.string()
16+
.url()
17+
.required('Обязательное поле')
18+
.test('no-duplicate', 'Эта лента уже добавлена', (value) => !state.rssFeed.includes(value));
19+
20+
const validateInput = (value) => {
21+
try {
22+
schema.validateSync(value, { abortEarly: false });
23+
return true;
24+
} catch (error) {
25+
if (error instanceof yup.ValidationError) {
26+
state.errors = error.errors;
27+
return false;
28+
}
29+
throw error;
30+
}
31+
};
32+
33+
export const updateInputValue = (value) => {
34+
state.inputValue = value;
35+
state.errors = null;
36+
};
37+
38+
export const addRssFeed = () => {
39+
if (validateInput(state.inputValue)) {
40+
state.rssFeed = [...state.rssFeed, state.inputValue];
41+
console.log("обновлён список rss", state.rssFeed);
42+
state.errors = null;
43+
} else {
44+
console.log("не прошёл валидацию:", state.errors);
45+
}
46+
};
47+
48+
49+
50+
51+
52+
53+
54+
55+
56+

0 commit comments

Comments
 (0)