1
+ // Define UI Element
2
+ const type = document . getElementById ( 'type' ) ;
3
+ const userInput = document . getElementById ( 'user-input' ) ;
4
+ const form = document . querySelector ( 'form' ) ;
5
+ const resultList = document . getElementById ( 'result-list' )
6
+
7
+ // Add EventListener
8
+ form . addEventListener ( 'submit' , handleSubmit ) ;
9
+ type . addEventListener ( 'change' , errorShow ) ;
10
+ userInput . addEventListener ( 'focus' , removeAlertInput )
11
+
12
+ function handleSubmit ( e ) {
13
+ e . preventDefault ( ) ;
14
+ if ( type . value !== 'null' && userInput . value ) {
15
+ // create element table row
16
+ const tr = document . createElement ( 'tr' ) ;
17
+
18
+ let regex = / ^ \d { 4 } $ /
19
+ let found = null
20
+ // check input
21
+ switch ( type . value ) {
22
+ case 'email' :
23
+ regex = / ^ [ \w -\. ] + [ \w ] @ ( [ \w - ] + \. ) + [ \w - ] { 2 , 4 } $ /
24
+ found = userInput . value . match ( regex ) ;
25
+ if ( found ) {
26
+ tr . innerHTML = `
27
+ <td>E-mail</td>
28
+ <td>${ userInput . value } </td>
29
+ <td><span class="alert-success py-2 px-3 rounded">Valid</span></td>
30
+ `
31
+ } else {
32
+ tr . innerHTML = `
33
+ <td>E-mail</td>
34
+ <td>${ userInput . value } </td>
35
+ <td><span class="alert-danger py-2 px-3 rounded">Invalid</span></td>
36
+ `
37
+ }
38
+ break
39
+ case 'phoneNumber' :
40
+ regex = / ^ ( \+ (? = 8 8 ) ) ? ( 8 8 ) ? 0 1 \d { 9 } $ /
41
+ found = userInput . value . match ( regex ) ;
42
+ if ( found ) {
43
+ tr . innerHTML = `
44
+ <td>Phone Number</td>
45
+ <td>${ userInput . value } </td>
46
+ <td><span class="alert-success py-2 px-3 rounded">Valid</span></td>
47
+ `
48
+ } else {
49
+ tr . innerHTML = `
50
+ <td>Phone Number</td>
51
+ <td>${ userInput . value } </td>
52
+ <td><span class="alert-danger py-2 px-3 rounded">Invalid</span></td>
53
+ `
54
+ }
55
+ break
56
+ case 'postCode' :
57
+ regex = / ^ \d { 4 } $ /
58
+ found = userInput . value . match ( regex ) ;
59
+ if ( found ) {
60
+ tr . innerHTML = `
61
+ <td>Post Code</td>
62
+ <td>${ userInput . value } </td>
63
+ <td><span class="alert-success py-2 px-3 rounded">Valid</span></td>
64
+ `
65
+ } else {
66
+ tr . innerHTML = `
67
+ <td>Post Code</td>
68
+ <td>${ userInput . value } </td>
69
+ <td><span class="alert-danger py-2 px-3 rounded">Invalid</span></td>
70
+ `
71
+ }
72
+ break
73
+ }
74
+ firstChild = resultList . firstElementChild
75
+ resultList . insertBefore ( tr , firstChild )
76
+ userInput . value = ''
77
+ } else if ( ! userInput . value ) {
78
+ userInput . classList . add ( 'is-invalid' ) ;
79
+ } else {
80
+ type . classList . add ( 'is-invalid' ) ;
81
+ userInput . value = ''
82
+ }
83
+ }
84
+
85
+ function errorShow ( ) {
86
+ type . classList . remove ( 'is-invalid' )
87
+ }
88
+
89
+ function removeAlertInput ( ) {
90
+ userInput . classList . remove ( 'is-invalid' )
91
+ }
0 commit comments