File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed
Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change 1+ export default class html5formValidation {
2+ constructor ( element = document . querySelector ( 'form' ) , settings = { } ) {
3+ this . settings = Object . assign (
4+ { } ,
5+ {
6+ errorElement : 'error' ,
7+ invalidClass : 'invalid' ,
8+ submitHandler : null ,
9+ validateOnInput : true
10+ } ,
11+ settings
12+ ) ;
13+ this . form = element ;
14+ this . errorDiv = `<div class="${ this . settings . errorElement } "></div>` ;
15+
16+ this . init ( ) ;
17+ }
18+
19+ init ( ) {
20+ this . form . noValidate = true ;
21+ this . settings . validateOnInput && this . validateAll ( this . form ) ;
22+
23+ this . form . onsubmit = event => {
24+ this . validateAll ( this . form ) ;
25+
26+ if ( ! this . form . checkValidity ( ) ) {
27+ event . preventDefault ( ) ;
28+ } else {
29+ if ( typeof this . settings . submitHandler === 'function' ) {
30+ event . preventDefault ( ) ;
31+
32+ this . settings . submitHandler ( this ) ;
33+ }
34+ }
35+ } ;
36+ }
37+
38+ validateAll ( form ) {
39+ const requiredFields = form . querySelectorAll ( '[required]' ) ;
40+
41+ for ( const field of requiredFields ) {
42+ this . validateField ( field ) ;
43+ }
44+ }
45+
46+ validateField ( field ) {
47+ field . insertAdjacentHTML ( 'afterend' , this . errorDiv ) ;
48+
49+ field . oninvalid = ( ) => {
50+ field . classList . add ( this . settings . invalidClass ) ;
51+ field . nextSibling . textContent = field . validationMessage ;
52+ }
53+
54+ field . oninput = ( ) => {
55+ field . nextSibling . textContent = '' ;
56+ field . classList . remove ( this . settings . invalidClass ) ;
57+ field . checkValidity ( ) ;
58+ }
59+ }
60+ }
61+ }
You can’t perform that action at this time.
0 commit comments