forked from leushin/yandexSchoolTest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
209 lines (185 loc) · 6.59 KB
/
index.js
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
"use strict";
var MyForm = {
/**
* Компоненты страницы
* @private
*/
_components: {
fio: document.querySelector('input[name=fio]'),
email: document.querySelector('input[name=email]'),
phone: document.querySelector('input[name=phone]'),
resultContainer: document.getElementById('resultContainer'),
submitButton: document.getElementById('submitButton')
},
/**
* Объект регулярных выражений
* @private
*/
_rules: {
fio: /^\s*([A-zА-яЁё]+\s+){2}[A-zА-яЁё-]+\s*$/i,
email: /^[A-Z0-9А-ЯёЁ.]+@ya(ndex)?\.(ru|ua|by|kz|com)$/i,
phone: /^\+7\([0-9]{3}\)[0-9]{3}-[0-9]{2}-[0-9]{2}$/i
},
/**
* Удаляет класс error у всех форм перед валидацией
* @private
*/
_clearErrorClass: function () {
var inputAll = document.querySelectorAll('input');
Object.keys(inputAll).forEach(function(inputKey) {
inputAll[inputKey].classList.remove('error');
});
},
/**
* Добавляет класс error всем полям, не прошедшим валидацию
* @param {Object} result
* @private
*/
_addErrorClass: function (result) {
result.errorFields.forEach(function (inputName) {
var errorInput = document.querySelector('input[name=' + inputName + ']');
errorInput.classList.add('error');
});
},
/**
* Возвращает сумму всех цифр номера телефона
* @param {String} phone Телефонный номер
* @returns {Number}
* @private
*/
_getAmountPhoneNumbers: function(phone) {
var phoneNumbersArr = phone.match(/[0-9]/g);
if(!phoneNumbersArr) {
return;
}
return phoneNumbersArr.reduce(function(sum, current) {
return +sum + +current;
});
},
/**
* Возвращает название файла ответа
* @returns {String}
* @private
*/
_getRandomResponse: function() {
var responses = ['error.json', 'progress.json', 'success.json'];
var randomKey = Math.floor(Math.random() * 3);
return responses[randomKey];
},
/**
* Возвращает гет строку из переданного объекта
* @param {Object} obj Объект
* @returns {String}
* @private
*/
_makeGetString: function(obj) {
var getString = '';
var counter = 0;
var delimiter = '';
Object.keys(obj).forEach(function(key) {
delimiter = (counter) ? '&' : '';
getString += delimiter + key + '=' + obj[key];
counter++;
});
return getString;
},
/**
* Отправка данных аяксом
* @private
*/
_sendAjax: function () {
var xhr = new XMLHttpRequest();
var _that = this;
var formData = this._makeGetString(this.getData());
xhr.onload = function() {
if(this.status === 200) {
var json = JSON.parse(this.responseText);
switch(json.status) {
case 'success':
_that._components.resultContainer.className = 'success';
_that._components.resultContainer.textContent = 'Success';
break;
case 'error':
_that._components.resultContainer.className = 'error';
_that._components.resultContainer.textContent = json.reason;
break;
case 'progress':
_that._components.resultContainer.className = 'progress';
setTimeout(function(){
xhr.open('GET', 'responses/' + _that._getRandomResponse() + '?' + formData);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.send();
}, json.timeout);
break;
}
}
};
xhr.open('GET', document.getElementById('myForm').getAttribute('action') + '?' + formData);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.send();
},
/**
* Валидация формы, возвращает объект с результатом валидации и массивом названий полей не прошедших валидацию
* @returns {Object}
* @public
*/
validate: function() {
var inputValid = {
fio: this._rules.fio.test(this._components.fio.value),
email: this._rules.email.test(this._components.email.value),
phone: this._rules.phone.test(this._components.phone.value) && this._getAmountPhoneNumbers(this._components.phone.value) <= 30
};
return {
isValid: Object.keys(inputValid).every(function(item){
return inputValid[item];
}),
errorFields: Object.keys(inputValid).filter(function(item){
return !inputValid[item];
})
};
},
/**
* Получает объект значений формы
* @returns {Object}
* @public
*/
getData: function() {
return {
fio: this._components.fio.value,
email: this._components.email.value,
phone: this._components.phone.value
}
},
/**
* Устанавливает значения переданного объекта значениям формы
* @param {Object} object
* @public
*/
setData: function(inputData) {
var realData = this.getData();
var settedData = Object.assign({}, realData, inputData);
this._components.fio.value = settedData.fio;
this._components.email.value = settedData.email;
this._components.phone.value = settedData.phone;
},
/**
* Метод, выполняющийся при сабмите формы
* @public
*/
submit: function() {
this._clearErrorClass();
var result = this.validate();
if(!result.isValid) {
this._addErrorClass(result);
} else {
this._components.submitButton.disabled = true;
this._sendAjax();
}
}
};
(function() {
document.getElementById('submitButton').addEventListener('click', function(e) {
e.preventDefault();
MyForm.submit();
});
})();