Skip to content

Commit f4b7802

Browse files
committed
Add demo
1 parent 3bb44a5 commit f4b7802

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

demo/index.html

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="utf-8" />
5+
6+
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
7+
8+
<title>HTML5 form validator</title>
9+
</head>
10+
<body>
11+
<form>
12+
<input type="number" value="" placeholder="Enter 42" min="42" max="42" required>
13+
<input type="email" placeholder="Enter your email" required>
14+
<button type="submit">Register</button>
15+
</form>
16+
17+
<script>
18+
class html5formValidation {
19+
constructor(element = document.querySelector('form'), settings = {}) {
20+
this.settings = Object.assign(
21+
{},
22+
{
23+
errorElement: 'error',
24+
invalidClass: 'invalid',
25+
submitHandler: null,
26+
validateOnInput: true
27+
},
28+
settings
29+
);
30+
this.form = element;
31+
this.errorDiv = `<div class="${this.settings.errorElement}"></div>`;
32+
33+
this.init();
34+
}
35+
36+
init() {
37+
this.form.noValidate = true;
38+
this.settings.validateOnInput && this.validateAll(this.form);
39+
40+
this.form.onsubmit = event => {
41+
this.validateAll(this.form);
42+
43+
if (!this.form.checkValidity()) {
44+
event.preventDefault();
45+
} else {
46+
if (typeof this.settings.submitHandler === 'function') {
47+
event.preventDefault();
48+
49+
this.settings.submitHandler(this);
50+
}
51+
}
52+
};
53+
}
54+
55+
validateAll(form) {
56+
const requiredFields = form.querySelectorAll('[required]');
57+
58+
for (const field of requiredFields) {
59+
this.validateField(field);
60+
}
61+
}
62+
63+
validateField(field) {
64+
field.insertAdjacentHTML('afterend', this.errorDiv);
65+
66+
field.oninvalid = () => {
67+
field.classList.add(this.settings.invalidClass);
68+
field.nextSibling.textContent = field.validationMessage;
69+
}
70+
71+
field.oninput = () => {
72+
field.nextSibling.textContent = '';
73+
field.classList.remove(this.settings.invalidClass);
74+
field.checkValidity();
75+
}
76+
}
77+
}
78+
</script>
79+
80+
<script>
81+
new html5formValidation()
82+
</script>
83+
</body>
84+
</html>

0 commit comments

Comments
 (0)