-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidation.js
84 lines (72 loc) · 2.69 KB
/
validation.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
// Get the form and all inputs
const form = document.getElementById('form')
const firstname_input = document.getElementById('firstname-input')
const email_input = document.getElementById('email-input')
const password_input = document.getElementById('password-input')
const repeat_password_input = document.getElementById('repeat-password-input')
const error_message = document.getElementById('error-message')
// Add an event listener to the form
form.addEventListener('submit', (e) => {
let errors = []
if(firstname_input){
// If we have a firstname input then we are in the signup
errors = getSignupFormErrors(firstname_input.value, email_input.value, password_input.value, repeat_password_input.value)
}
else{
// If we don't have a firstname input then we are in the login
errors = getLoginFormErrors(email_input.value, password_input.value)
}
if(errors.length > 0){
// If there are any errors
e.preventDefault()
error_message.innerText = errors.join(". ")
}
})
// Function to get the errors in the signup form
function getSignupFormErrors(firstname, email, password, repeatPassword){
let errors = []
if(firstname === '' || firstname == null){
errors.push('Firstname is required')
firstname_input.parentElement.classList.add('incorrect')
}
if(email === '' || email == null){
errors.push('Email is required')
email_input.parentElement.classList.add('incorrect')
}
if(password === '' || password == null){
errors.push('Password is required')
password_input.parentElement.classList.add('incorrect')
}
if(password.length < 8){
errors.push('Password must have at least 8 characters')
password_input.parentElement.classList.add('incorrect')
}
if(password !== repeatPassword){
errors.push('Password does not match repeated password')
password_input.parentElement.classList.add('incorrect')
repeat_password_input.parentElement.classList.add('incorrect')
}
return errors;
}
// Function to get the errors in the login form
function getLoginFormErrors(email, password){
let errors = []
if(email === '' || email == null){
errors.push('Email is required')
email_input.parentElement.classList.add('incorrect')
}
if(password === '' || password == null){
errors.push('Password is required')
password_input.parentElement.classList.add('incorrect')
}
return errors;
}
const allInputs = [firstname_input, email_input, password_input, repeat_password_input].filter(input => input != null)
allInputs.forEach(input => {
input.addEventListener('input', () => {
if(input.parentElement.classList.contains('incorrect')){
input.parentElement.classList.remove('incorrect')
error_message.innerText = ''
}
})
})