-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
100 lines (68 loc) · 2.23 KB
/
script.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
const form = document.getElementById('form');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password2 = document.getElementById('password2');
form.addEventListener('submit', (e) => {
e.preventDefault();
checkInputs();
});
function checkInputs(){
//get values from inputs
const usernameValue = username.value.trim();
const emailValue = email.value.trim();
const passwordValue = password.value.trim();
const password2Value = password2.value.trim();
if(usernameValue === ''){
//show error & add error class
setErrorFor(username, 'Username cannot be blank');
}
else{
//add success class
setSuccessFor(username);
}
if(emailValue === ''){
setErrorFor(email, 'Email cannot be blank');
}
else if(!isEmail(emailValue)){
setErrorFor(email, 'Email is not valid');
}
else{
setSuccessFor(email);
}
if(passwordValue === ''){
setErrorFor(password, 'Password cannot be blank');
}
else{
setSuccessFor(password);
}
if(password2Value === ''){
setErrorFor(password2, 'Password check cannot be blank');
}
else if(passwordValue !== password2Value){
setErrorFor(password2, 'Passwords does not match');
}
else{
setSuccessFor(password2);
}
//last success message
const btn = document.querySelector('button');
btn.innerHTML = 'Validated Successfully ✔';
}
function setErrorFor(input, message){
const formControl = input.parentElement; //.form-control
const small = formControl.querySelector('small');
//add error msg inside small
small.innerText = message;
//add error class
formControl.className = 'form-control error';
}
function setSuccessFor(input){
//select the div .form-control
const formControl = input.parentElement;
//add sucess class
formControl.className = 'form-control success';
}
function isEmail(email){
return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);
}