-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
89 lines (78 loc) · 2.57 KB
/
script.js
File metadata and controls
89 lines (78 loc) · 2.57 KB
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
const form = document.getElementById("registration-form");
const username = document.getElementById("username");
const email = document.getElementById("email");
const password = document.getElementById("password");
const confirmPassword = document.getElementById("confirmPassword");
form.addEventListener("submit", function (current){
current.preventDefault();
const isRequiredValid = checkRequired([username,email,password,confirmPassword]);
let isFormValid = isRequiredValid;
if(isRequiredValid){
const isUsernameValid = checkLength(username,3,15);
const isEmailValid = checkEmail(email);
const isPasswordValid = checkLength(password,6,25);
const isPasswordMatch = checkPasswordsMatch(password,confirmPassword);
isFormValid = isUsernameValid && isEmailValid && isPasswordValid && isPasswordMatch ;
}
if(isFormValid){
alert("Registration successful!");
form.reset();
document.querySelectorAll(".form-group").forEach((group)=> {
group.className = "form-group";
});
}
});
function checkPasswordsMatch(input1,input2){
if(input1.value !== input2.value){
showError(input2,"Password do not match");
return false;
}else{
return true;
}
}
function checkEmail(email){
// Email regex that covers most common email formats
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if(emailRegex.test(email.value.trim())){
showSuccess(email);
return true;
}else{
showError(email,"Email is not Valid");
return false;
}
}
function checkLength(input,min,max){
if(input.value.length < min){
showError(input,`${formatFieldName(input)} must be at least ${min} `);
return false;
}else if(input.value.length > max){
showError(input,`${formatFieldName(input)} must be less than ${max} `);
return false;
}else{
showSuccess(input);
return true;
}
}
function checkRequired(inputArray){
let isValid = true;
inputArray.forEach(input => {
if(input.value.trim() === ""){
showError(input , `${formatFieldName(input)} is required`);
isValid = false;
}
});
return isValid;
}
function formatFieldName(input){
return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}
function showError(input,massage){
const formGroup = input.parentElement;
formGroup.className = "form-group error";
const span = formGroup.querySelector("span");
span.innerText = massage;
}
function showSuccess(input){
const formGroup = input.parentElement;
formGroup.className = "form-group success";
}