This repository was archived by the owner on Mar 21, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
121 lines (106 loc) · 3.75 KB
/
index.js
File metadata and controls
121 lines (106 loc) · 3.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
let Fields = {
form: document.getElementById('myForm'),
fio: document.querySelector('input[name=fio]'),
email: document.querySelector('input[name=email]'),
phone: document.querySelector('input[name=phone]'),
submit: document.getElementById('submitButton')
};
const container = document.getElementById('resultContainer');
// var для выполнения условия с глобальной областью видимости
var MyForm = {
validate() {
let errorFields = [],
isValid = true;
let checkValidity = {
// ровно три слова
fio: (Fields.fio.value.trim().split(/\s+/).length == 3),
// RFC 5322 (только для валидации имени почты)
email: (/(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(yandex(?:\.(ru|ua|by|kz|com))|(?:ya\.ru))/.test(Fields.email.value)),
// формат +7(999)999-99-99 и сумма цифр не превышает 30
phone: (/\+7\(\d{3}\)\d{3}-\d{2}-\d{2}/.test(Fields.phone.value) &&
Fields.phone.value.match(/\d/g).reduce((acc, val) => acc + +val, 0) <= 30), // parseInt(val);
};
for (let key in checkValidity) {
if (!checkValidity[key]) {
isValid = false;
errorFields.push(key);
}
}
return {
isValid,
errorFields
};
},
getData() {
return {
fio: Fields.fio.value,
email: Fields.email.value,
phone: Fields.phone.value
};
},
setData(fields) {
// в данном случае Object.prototype.toString более корректен нежели typeof
if (Object.prototype.toString.call(fields) === '[object Object]') {
Fields.fio.value = fields.fio;
Fields.email.value = fields.email;
Fields.phone.value = fields.phone;
} else {
return 'Неверный формат!';
}
return;
},
submit() {
let {isValid, errorFields} = this.validate();
let fields = this.getData();
Object.keys(fields).forEach(field => Fields[field].classList.remove('error'));
if (isValid) {
Fields.submit.disabled = true;
fetchRequest();
} else {
errorFields.forEach(field => Fields[field].classList.add('error'));
}
}
};
function getRandomURL() {
let random = Math.floor(Math.random() * 3);
switch (random) {
case 0:
return '/error.json';
case 1:
return '/success.json';
case 2:
return '/progress.json';
}
}
function fetchRequest() {
container.classList.remove('error', 'success', 'progress');
const url = getRandomURL();
return fetch(Fields.form.action + url)
.then(res => res.json())
.then(data => {
// для проверки ответов от сервера и обновления стилей
// Fields.submit.disabled = false;
switch (data.status) {
case 'error':
container.classList.add('error');
container.innerText = data.reason || 'Произошла ошибка на сервере!';
break;
case 'success':
container.classList.add('success');
container.innerText = 'Успешно!';
break;
case 'progress':
container.classList.add('progress');
container.innerText = 'Подождите, идет загрузка!';
setTimeout(() => fetchRequest(), data.timeout);
break;
}
})
.catch(err => console.error(err));
}
document.addEventListener('DOMContentLoaded', () => {
Fields.form.onsubmit = (e) => {
e.preventDefault();
MyForm.submit();
};
});