File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ const form = document . getElementById ( "myForm" ) ;
2+ const nameInput = document . getElementById ( "name" ) ;
3+ const emailInput = document . getElementById ( "email" ) ;
4+ const passwordInput = document . getElementById ( "password" ) ;
5+ const successMsg = document . getElementById ( "successMsg" ) ;
6+
7+ form . addEventListener ( "submit" , function ( e ) {
8+ e . preventDefault ( ) ; // stop default submit
9+ let valid = true ;
10+
11+ // Reset messages
12+ document . querySelectorAll ( "small.error" ) . forEach ( err => err . textContent = "" ) ;
13+ successMsg . textContent = "" ;
14+
15+ // Name validation
16+ if ( nameInput . value . trim ( ) === "" ) {
17+ setError ( nameInput , "Name is required" ) ;
18+ valid = false ;
19+ }
20+
21+ // Email validation
22+ if ( ! validateEmail ( emailInput . value ) ) {
23+ setError ( emailInput , "Enter a valid email" ) ;
24+ valid = false ;
25+ }
26+
27+ // Password validation
28+ if ( passwordInput . value . length < 6 ) {
29+ setError ( passwordInput , "Password must be at least 6 characters" ) ;
30+ valid = false ;
31+ }
32+
33+ // If all valid
34+ if ( valid ) {
35+ successMsg . textContent = "Form submitted successfully!" ;
36+ form . reset ( ) ;
37+ }
38+ } ) ;
39+
40+ function setError ( input , message ) {
41+ const formControl = input . parentElement ;
42+ const errorMsg = formControl . querySelector ( "small.error" ) ;
43+ errorMsg . textContent = message ;
44+ }
45+
46+ function validateEmail ( email ) {
47+ const re = / ^ [ ^ \s @ ] + @ [ ^ \s @ ] + \. [ ^ \s @ ] + $ / ;
48+ return re . test ( String ( email ) . toLowerCase ( ) ) ;
49+ }
You can’t perform that action at this time.
0 commit comments