-
Notifications
You must be signed in to change notification settings - Fork 0
/
p-form.js
257 lines (206 loc) · 5.79 KB
/
p-form.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import {LitElement, html} from 'https://cdn.jsdelivr.net/gh/lit/dist@2/core/lit-core.min.js';
// DOCS: https://github.com/Hi-Pyncho/web-components#form
class Validator {
constructor(prefix = '') {
this.prefix = `${prefix}-`
}
validateText(input) {
const value = input.value
if(value === '') {
this.setInvalid(input)
return false
}
this.unsetInvalid(input)
return true
}
validatePhone(input) {
const value = input.value
if(!this.validateText(input)) return
const isPhoneValid = value.match(/\d/g).length === 11
if(!isPhoneValid) {
this.setInvalid(input)
return false
}
this.unsetInvalid(input)
return true
}
validateEmail(input) {
const value = input.value
if(!this.validateText(input)) return
const isEmailValid = /.+@.+\..+/g.test(value)
if(!isEmailValid) {
this.setInvalid(input)
return false
}
this.unsetInvalid(input)
return true
}
validateCheckbox(input) {
if(!input.checked) {
this.setInvalid(input)
return false
}
this.unsetInvalid(input)
return true
}
setInvalid(input) {
input.classList.add(`${this.prefix}invalid`)
}
unsetInvalid(input) {
input.classList.remove(`${this.prefix}invalid`)
}
}
class Form {
constructor({form, fields, errorContainerClass, formWrapper, successText, failText, backendHandler}) {
this.form = form
this.fields = fields,
this.errorContainerClass = errorContainerClass
this.formWrapper = formWrapper
this.successText = successText
this.failText = failText
this.backendHandler = backendHandler
this.validator = new Validator('p')
this.detail = {
form: this.form,
}
}
addFormListener() {
this.form.addEventListener('submit', (event) => this.onSubmitHanlder(event))
}
markError(input) {
const name = input.name
const inputWrapper = input.closest(this.errorContainerClass)
inputWrapper.setAttribute('data-error', this.fields[name].errorMessage)
}
unmarkError(input) {
const errorContainer = input.closest(this.errorContainerClass)
this.validator.unsetInvalid(input)
errorContainer.removeAttribute('data-error')
}
addInputListeners() {
Object.entries(this.fields).forEach(([name, {type}]) => {
switch (type) {
case 'text':
case 'tel':
case 'email':
this.form[name].addEventListener('input', () => this.unmarkError(this.form[name]))
break;
case 'checkbox':
this.form[name].addEventListener('change', () => this.unmarkError(this.form[name]))
break;
}
})
}
validateInput(input, type) {
switch (type) {
case 'text':
return this.validator.validateText(input)
case 'email':
return this.validator.validateEmail(input)
case 'tel':
return this.validator.validatePhone(input)
case 'checkbox':
return this.validator.validateCheckbox(input)
}
}
validateAllInputs() {
const validatedInputs = Object.entries(this.fields).reduce((acc, [field, {type}]) => {
const input = this.form[field]
if(this.validateInput(input, type)) {
acc.push(true)
} else {
this.markError(input)
acc.push(false)
}
return acc
}, [])
return validatedInputs.every(Boolean)
}
createResultMessage(text) {
const textBlock = document.createElement('p')
textBlock.classList.add('p-result-message')
textBlock.textContent = text
return textBlock
}
async onSubmitHanlder(event) {
event.preventDefault()
const isFormValid = this.validateAllInputs()
if(!isFormValid) return
this.form.dispatchEvent(new CustomEvent('afterSuccessValidation', {
detail: this.detail
}))
if(this.backendHandler === '') return
let result
try {
result = await this.sendData()
} catch (error) {
this.form.replaceWith(this.createResultMessage(this.failText))
return
}
if(result && result.answer === 'success') {
this.form.replaceWith(this.createResultMessage(this.successText))
return
}
}
async sendData() {
const formData = new FormData(this.form)
const response = await fetch(this.backendHandler, {
method: 'POST',
body: formData,
});
const request = await response.json();
return request
}
init() {
this.addFormListener()
this.addInputListeners()
}
}
customElements.define('p-form', class extends LitElement {
static properties = {
successText: String,
failText: String,
backendHandler: String,
}
constructor() {
super();
this.successText = ''
this.failText = ''
this.backendHandler = ''
}
firstUpdated() {
const formWrapper = this.shadowRoot.querySelector('[part="form-wrapper"]')
const form = this.getSlottedByName()[0]
form.setAttribute('novalidate', true)
const rawFields = form.querySelectorAll('[data-validate]')
const preparedFields = Array.from(rawFields).reduce((acc, field) => {
acc[field.name] = {
'type': field.dataset.type,
'errorMessage': field.dataset.errormessage,
}
return acc
}, {})
const formInstance = new Form({
'form': form,
'fields': preparedFields,
'formWrapper': formWrapper,
'errorContainerClass': 'label',
'successText': this.successText,
'failText': this.failText,
'backendHandler': this.backendHandler,
})
formInstance.init()
}
getSlottedByName(name = '') {
const search = name.trim() === '' ? 'slot' : `slot[name='${name}']`
const slot = this.shadowRoot.querySelector(search)
return slot.assignedElements({flatten: true})
}
render() {
return html`
<div part='form-wrapper'>
<slot></slot>
</div>
`
}
})