-
Notifications
You must be signed in to change notification settings - Fork 0
/
validation.js
47 lines (41 loc) · 1.41 KB
/
validation.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
/* Password validation rules:
* Letters & numbers & only these symbols !@#$&*
* Must have at least 1 letter, 1 number and 1 of the above symbols
* Can't have 3 consecutive numbers in accending order, example 123 or 890
*/
var MyInput = class extends HTMLElement {
constructor() {
super();
const template = document.getElementById('my-input');
const templateContent = template.content;
this.el = this.attachShadow({mode: 'open'});
this.el.appendChild(templateContent.cloneNode(true));
this.inputEl = this.el.querySelector('#input');
}
connectedCallback() {
this.el.querySelector('#input').addEventListener('keyup', this.handleKeyDown);
}
handleKeyDown = (e) => {
const isValid = this.validate();
if (!isValid) {
if (this.el.querySelector('[name=validation-type]:checked').value === 'number') {
this.inputEl.setCustomValidity('Only numbers');
} else {
this.inputEl.setCustomValidity('Only letters');
}
this.inputEl.reportValidity();
} else {
this.inputEl.setCustomValidity('');
this.inputEl.reportValidity();
}
}
validate() {
if (this.el.querySelector('[name=validation-type]:checked').value === 'number') {
if (/[^0-9]/.test(this.inputEl.value)) return false;
} else {
if (/[^a-zA-Z]/.test(this.inputEl.value)) return false;
}
return true;
}
}
customElements.define('my-input', MyInput);