0% found this document useful (0 votes)
18 views

WD - Notes-Unit-4 (Half Unit)

The document discusses arrays in JavaScript. Some key points: - Arrays allow storing multiple values in a single variable and accessing them via indexes. They can store any data type. - There are two ways to declare an array: using array literal syntax like let arr = [1,2,3] or the Array constructor like let arr = new Array(1,2,3). - Array elements can be accessed and modified by their index. The length property returns the number of elements. Common methods for manipulating arrays include push(), pop(), shift(), unshift(), splice(), slice(), and concat().

Uploaded by

NeeharikaPandey
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

WD - Notes-Unit-4 (Half Unit)

The document discusses arrays in JavaScript. Some key points: - Arrays allow storing multiple values in a single variable and accessing them via indexes. They can store any data type. - There are two ways to declare an array: using array literal syntax like let arr = [1,2,3] or the Array constructor like let arr = new Array(1,2,3). - Array elements can be accessed and modified by their index. The length property returns the number of elements. Common methods for manipulating arrays include push(), pop(), shift(), unshift(), splice(), slice(), and concat().

Uploaded by

NeeharikaPandey
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Web Designing

Unit-4
Arrays in Javascript:
Introduction: Arrays are complex variables that allow us to store more than one value or
a group of values under a single variable name. JavaScript arrays can store any valid
value, including strings, numbers, objects, functions, and even other arrays, thus making
it possible to create more complex data structures such as an array of objects or an array
of arrays.
Arrays are used when we have a list of items. An array allows you to store several values
with the same name and access them by using their index number.
Declaration of an Array
There are basically two ways to declare an array.
1. Creating an array:
(i) let arrayName = [value1, value2, ...];
Example:
let courses = ["HTML", "CSS", "Javascript", "React"];
console.log(courses) or document.write(courses);
Output:
"HTML", "CSS", "Javascript", "React"
(ii) Array can also be created using the Array() constructor as shown in the following
syntax.
Syntax: var myArray = new Array(element0, element1, ..., elementN);
Example: let arr1 = new Array(3)
arr1[0] = 10
arr1[1] = 20
arr1[2] = 30
console.log("Array 1: ", arr1)
Output:Array 1: [ 10, 20, 30 ]
2. Accessing the Elements of an Array
Array elements can be accessed by their index using the square bracket notation. An index
is a number that represents an element's position in an array.
Array indexes are zero-based. This means that the first item of an array is stored at index
0, not 1, the second item is stored at index 1, and so on. Array indexes start at 0 and go up
to the number of elements minus 1. So, array of five elements would have indexes from 0
to 4.
Example: var fruits = ["Apple", "Banana", "Mango", "Orange",
"Papaya"]; document.write(fruits[0]); // Prints: Apple
document.write(fruits[1]); // Prints: Banana
document.write(fruits[2]); // Prints: Mango //
Output:
Apple
Banana
Mango
3. Getting the Length of an Array
The length property returns the length of an array, which is the total number of elements
contained in the array. Array length is always greater than the index of any of its element.
Example: var fruits = ["Apple", "Banana", "Mango", "Orange",
"Papaya"]; document.write(fruits.length); // Prints: 5
4. Looping Through Array Elements
You can use for loop to access each element of an array in sequential order.
Example: var fruits = ["Apple", "Banana", "Mango", "Orange",
"Papaya"]; // Iterates over array elements
for(var i = 0; i < fruits.length; i++)
{ document.write(fruits[i] + "<br>"); // Print array element
5. Adding New Elements to an Array
To add a new element at the end of an array, simply use the push() method.
Example: var colors = ["Red", "Green", "Blue"];
colors.push("Yellow");
document.write(colors);
Output: Red, Green, Blue, Yellow
To add a new element at the beginning of an array use the unshift() method.
Example:
var colors = ["Red", "Green", "Blue"]; colors.unshift("Yellow");
It will yellow at the beginning of array named colors.
6. Removing Elements from an Array
(i) To remove the last element from an array you can use the pop() method. This method
returns the value that was popped out.
Example: var colors = ["Red", "Green", "Blue"];
var last = colors.pop();
document.write(colors);
Output: Red, Green
(ii) To remove the first element from an array using the shift() method. This method
also returns the value that was shifted out.
Example: var colors = ["Red", "Green", "Blue"];
var first = colors.shift();
document.write(first); // Prints: Red
document.write(colors.length);
7. Adding or Removing Elements at Any Position
The splice() method is a very versatile array method that allows you to add or remove
elements from any index, using the syntax
arr.splice(startIndex, deleteCount, elem1, ..., elemN).
This method takes three parameters: the first parameter is the index at which to start
splicing the array, it is required; the second parameter is the number of elements to
remove (use 0 if you don't want to remove any elements), it is optional; and the third
parameter is a set of replacement elements, it is also optional.
Example: var colors = ["Red", "Green", "Blue"];
var removed = colors.splice(0,1); // Remove the first element
document.write(colors); // Prints: Green,Blue
document.write(removed); // Prints: Red (one item array)
document.write(removed.length); // Prints: 1
removed = colors.splice(1, 0, "Pink", "Yellow"); // Insert two
items at position one document.write(colors); // Prints:
Green,Pink,Yellow,Blue document.write(removed); // Empty array
document.write(removed.length); // Prints: 0
removed = colors.splice(1, 1, "Purple", "Voilet"); // Insert two
values, remove one
document.write(colors); //Prints:
Green,Purple,Voilet,Yellow,Blue
document.write(removed); // Prints: Pink (one item array)
document.write(removed.length); // Prints: 1
Output: Green,Blue
Red
1
Green,Pink,Yellow,Blue

0
Green,Purple,Voilet,Yellow,Blue
Pink
1
7. Creating a String from an Array
There may be situations where you simply want to create a string by joining the elements
of an array. To do this you can use the join() method. This method takes an optional
parameter which is a separator string that is added in between each element. If you omit
the separator, then JavaScript will use comma (,) by default.
Example:
var colors = ["Red", "Green", "Blue"];
document.write(colors.join()); // Prints: Red,Green,Blue
document.write(colors.join("")); // Prints: RedGreenBlue
document.write(colors.join("-")); // Prints: Red-Green-Blue
document.write(colors.join(", "));
8. Extracting a Portion of an Array
If you want to extract out a portion of an array (i.e. subarray) but keep the original array
intact you can use the slice() method. This method takes 2 parameters: start index (index
at which to begin extraction), and an optional end index (index before which to end
extraction), like arr.slice(startIndex, endIndex)
Example:
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
var subarr = fruits.slice(1, 3);
document.write(subarr); // Prints: Banana,Mango
9. Merging Two or More Arrays
The concat() method can be used to merge or combine two or more arrays. This method
does not change the existing arrays, instead it returns a new array.
Example: var pets = ["Cat", "Dog", "Parrot"];
var wilds = ["Tiger", "Wolf", "Zebra"]; // Creating new array
by combining pets and wilds arrays
var animals = pets.concat(wilds);
document.write(animals);
Output: Cat,Dog,Parrot,Tiger,Wolf,Zebra
10. Searching Through an Array
(i) If you want to search an array for a specific value, you can simply use
the indexOf() and lastIndexOf(). If the value is found, both methods return an index
representing the array element. If the value is not found, -1 is returned.
The indexOf() method returns the first one found, whereas the lastIndexOf() returns the
last one found.
Example:
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
document.write(fruits.indexOf("Apple")); // Prints: 0
document.write(fruits.indexOf("Banana")); // Prints: 1
document.write(fruits.indexOf("Pineapple")); // Prints: -1
(ii) You can also use includes() method to find out whether an array includes a certain
element or not. This method takes the same parameters
as indexOf() and lastIndexOf() methods, but it returns true or false instead of index
number.
For example:
var arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
document.write(arr.includes(1)); // Prints: true
document.write(arr.includes(6)); // Prints: false
document.write(arr.includes(1, 2)); // Prints: true
document.write(arr.includes(3, 4)); // Prints: false
(iii) There is one more method similar to find() is findIndex() method, which returns the
index of a found element in the array instead of its value.
The find() method only looks for the first element that satisfies the provided testing
function. However, if you want to find out all the matched elements you can use
the filter() method.
The filter() method creates a new array with all the elements that successfully passes the
given test.
Example: var arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
var result = arr.filter(function(element) { return element >
4; }); document.write(result); // Prints: 5,7
document.write(result.length); // Prints: 2
Javascript Functions:
A function is a group of statements that perform specific tasks and can be kept and
maintained separately form main program. Functions provide a way to create reusable
code packages which are more portable and easier to debug. Here are some advantages of
using functions:
• Functions reduces the repetition of code within a program — Function allows you to
extract commonly used block of code into a single component. Now you can perform the
same task by calling this function wherever you want within your script without having to
copy and paste the same block of code again and again.
• Functions makes the code much easier to maintain — Since a function created once
can be used many times, so any changes made inside a function automatically
implemented at all the places without touching the several files.
• Functions makes it easier to eliminate the errors — When the program is subdivided
into functions, if any error occur you know exactly what function causing the error and
where to find it. Therefore, fixing errors becomes much easier.
Defining and Calling a Function
The declaration of a function start with the function keyword, followed by the name of
the function you want to create, followed by parentheses i.e. () and finally place your
function's code between curly brackets {}
Syntax: function functionName() {
// Code to be executed
}
Example: // Defining function function sayHello()
{ alert("Hello, welcome to this website!"); } // Calling
function sayHello(); // 0utputs: Hello, welcome to this website!
Adding Parameters to Functions
You can specify parameters when you define your function to accept input values at run
time. The parameters work like placeholder variables within a function; they're replaced
at run time by the values (known as argument) provided to the function at the time of
invocation.
Syntax: function functionName(parameter1, parameter2, parameter3)
{
// Code to be executed
}
Example: // Defining function function displaySum(num1, num2)
{ var total = num1 + num2;
alert(total); } // Calling function
displaySum(6, 20); // 0utputs: 26
displaySum(-5, 17); // 0utputs: 12
Default Values for Function Parameters
Specify default values to the function parameters. This means that if no arguments are
provided to function when it is called these default parameters values will be used. This is
one of the most awaited features in JavaScript.
Example: function sayHello(name = 'Guest') { alert('Hello, '
+ name); } sayHello(); // 0utputs: Hello, Guest
sayHello('John'); // 0utputs: Hello, John
Returning Values from a Function
A function can return a value back to the script that called the function as a result using
the return statement. The value may be of any type, including arrays and objects.
The return statement usually placed as the last line of the function before the closing curly
bracket and ends it with a semicolon.
Example: // Defining function function getSum(num1, num2)
{ var total = num1 + num2;
return total; } // Displaying returned value alert(getSum(6,
20)); // 0utputs: 26
alert(getSum(-5, 17)); // 0utputs: 12
JavaScript Object
JavaScript is an object-based language and in JavaScript almost everything is an object or
acts like an object. So, to work with JavaScript effectively and efficiently we need to
understand how objects work as well as how to create your own objects and use them.
A JavaScript object is just a collection of named values. These named values are usually
referred to as properties of the object.
Creating Objects
An object can be created with curly brackets {} with an optional list of properties. A
property is a "key: value" pair, where the key (or property name) is always a string, and
value (or property value) can be any data type, like strings, numbers, Booleans or
complex data type like arrays, functions, and other objects. Additionally, properties with
functions as their values are often called methods to distinguish them from other
properties.
Syntax:
new Object(value)
Object(value)
let object_name = {
key_name : value,
...
}
Note:- Object() can be called with or without new. Both create a new object.
Example:
var person = { name: "Peter", age: 28, gender: "Male",
displayName: function() { alert(this.name); } };
Accessing Object's Properties
To access or get the value of a property, you can use the dot (.), or square bracket ([])
notation
Example: var book = { "name": "Harry Potter and the Goblet of
Fire", "author": "J. K. Rowling", "year": 2000 }; // Dot
notation document.write(book.author); // Prints: J. K.
Rowling // Bracket notation document.write(book["year"]); //
Prints: 2000
The dot notation is easier to read and write, but it cannot always be used. If the name of
the property is not valid (i.e. if it contains spaces or special characters), you cannot use
the dot notation; you'll have to use bracket notation. The square bracket notation offers
much more flexibility than dot notation. It also allows you to specify property names as
variables instead of just string literals.
Example: var person = { name: "Peter", age: 28, gender: "Male" };
var key = prompt("Enter any property name to get its value");
alert(person[key]); // Outputs: Peter (if enter "name")
Looping Through Object's Properties
You can iterate through the key-value pairs of an object using the for...in loop. This loop
is specially optimized for iterating over object's properties.
Example:
var person = { name: "Peter", age: 28, gender: "Male" }; //
Iterating over object properties
for(var i in person) { document.write(person[i] + "<br>"); //
Prints: name, age and gender }
Inherited Properties:
Inherited properties of an object are those properties that have been inherited from the
object’s prototype, as opposed to being defined for the object itself, which is known as the
object’s Own property. To verify if a property is an object’s Own property, we can use
the hasOwnProperty method.
Property Attributes Data properties in JavaScript have four attributes.
1. value: The property’s value.
2. writable: When true, the property’s value can be changed
3. enumerable: When true, the property can be iterated over by “for-in” enumeration.
Otherwise, the property is said to be non-enumerable.
4. configurable: If false, attempts to delete the property, change the property to be an
access-or property, or change its attributes (other than [[Value]], or changing
[[Writable]] to false) will fail.
5. Deleting Properties: To Delete a property of an object we can make use of the delete
operator.
Example: let obj1 = {
propfirst : "Name"
}// Output : Name
console.log(obj1.propfirst);
delete obj1.propfirst
// Output : undefined
console.log(obj1.propfirst);
Form Validation
Before submitting data to the server, you should check the data in the web browser to
ensure that the submitted data is in the correct format.
To provide quick feedback, you can use JavaScript to validate data. This is called client-
side validation.
If you don’t carry the client-side validation, it may cause a bad user experience. In this
case, you may feel a noticeable delay because it takes time for the form data to transfer
between the web browsers and the server.
Unlike the client-side validation that performs in the web browser, the server-side
validation is performed on the server. It’s critical always to implement the server-side
validation.
The reason is that client-side validation is quite easy to bypass. Malicious users can
disable JavaScript and submit bad data to your server.
Client-side validation options
When it comes to client-side validation, you’ll have two options:
•JavaScript validation: you develop the validation logic using JavaScript. Or you
can use a library to do so.
•Built-in form validation: you can use the HTML5 form validation features. This
validation has a better performance than JavaScript validation. However, it isn’t as
customizable as JavaScript validation.
JavaScript validation
You will create a simple signup form with four input fields: username, email, password,

and confirm password.


When you click the sign up without filling anything or filling incorrect data format, the
form will show error messages:
Create the project structure
• First, create the form-validation folder that stores all the source code files of the
project.
• Second, create the js and css folders inside the form-validation folder.
• Third, create the style.css in the css folder, the app.js in the js folder,
and index.html directly in the form-validation folder.
Build the HTML form
First, open the index.html file and enter the following code:
<!DOCTYPE html>
<html> <head>
<title>JavaScript Form Validation Demo</title>
<link rel="stylesheet" href="css/style.css"> </head>
<body>
<div class="container">
<form id="signup" class="form"> <h1>Sign Up</h1>
<div class="form-field"> <label
for="username">Username:</label> <input type="text"
name="username" id="username" autocomplete="off">
<small></small>
</div> <div class="form-field">
<label for="email">Email:</label>
<input type="text" name="email" id="email" autocomplete="off">
<small></small> </div>
<div class="form-field"> <label for="password">Password:</label>
<input type="password" name="password" id="password"
autocomplete="off"> <small></small>
</div> <div class="form-field"> <label for="confirm-
password">Confirm Password:</label>
<input type="password" name="confirm-password" id="confirm-
password" autocomplete="off">
<small></small> </div>
<div class="form-field"> <input type="submit" value="Sign Up">
</div> </form> </div>
<script src="js/app.js"></script>
</body>
</html>
Each form field has three elements:
•A label
•An input field
•A <small> element
If an input field isn’t valid, we’ll make its border color red by adding the error class to
the form-field element. It’ll look like this:
<div class="form-field error">
<label for="username">Username:</label>
<input type="text" name="username" id="username"
autocomplete="off">
<small></small> </div>
If the value of an input field is valid, then we’ll make its border color green by adding
the success class to the form-field element as follows:
<div class="form-field success">
<label for="username">Username:</label>
<input type="text" name="username" id="username"
autocomplete="off">
<small></small>
</div>
Develop utility functions
Before validating the form, you can develop some reusable utility functions to check if:
•A field is required.
•The length of a field is between min and max.
•The email is in a valid format.
•The password is strong.
Code for Validating input functions:
1) Validate the username field
The following checkUsername() function uses:
•The isRequired() function to check if the username is provided.
•The isBetween() function to check if the length of the username is between 3 and
25 characters.
•The showError() and showSuccess() functions to show the error and success
indicator.
The function returns true if the field passes the checks.
const checkUsername = () => {
let valid = false;
const min = 3,
max = 25;
const username = usernameEl.value.trim();
if (!isRequired(username)) {
showError(usernameEl, 'Username cannot be blank.');
} else if (!isBetween(username.length, min, max)) {
showError(usernameEl, `Username must be between $
{min} and ${max} characters.`)
} else {
showSuccess(usernameEl);
valid = true;
}
return valid;
}
2) Validate the email field
The checkEmail() function returns true if the email is provided and valid.
It uses the isRequired() and isEmailValid() functions for checking. And it uses
the showError() and showSuccess() functions to provide feedback in case of error and
success.
const checkEmail = () => {
let valid = false;
const email = emailEl.value.trim();
if (!isRequired(email)) {
showError(emailEl, 'Email cannot be blank.');
} else if (!isEmailValid(email)) {
showError(emailEl, 'Email is not valid.')
} else {
showSuccess(emailEl);
valid = true;
}
return valid;
}
3) Validate the password field
The following checkPassword() function checks the password field if it is provided and
match the required format:
const checkPassword = () => {
let valid = false;
const password = passwordEl.value.trim();
if (!isRequired(password)) {
showError(passwordEl, 'Password cannot be blank.');
} else if (!isPasswordSecure(password)) {
showError(passwordEl, 'Password must has at least 8
characters that include at least 1 lowercase character, 1
uppercase characters, 1 number, and 1 special character in
(!@#$%^&*)');
} else {
showSuccess(passwordEl);
valid = true;
}
return valid;
};
4) Validate the confirm password field
The checkConfirmPassword() function checks if the confirm password is the same as the
password.
const checkConfirmPassword = () => {
let valid = false;
// check confirm password
const confirmPassword = confirmPasswordEl.value.trim();
const password = passwordEl.value.trim();
if (!isRequired(confirmPassword)) {
showError(confirmPasswordEl, 'Please enter the password
again');
} else if (password !== confirmPassword) {
showError(confirmPasswordEl, 'Confirm password does not
match');
} else {
showSuccess(confirmPasswordEl);
valid = true;
}
return valid;
};
5. Modifying the submit event handler
Now, you can use the functions that validate the input fields in the submit event handler:
form.addEventListener('submit', function (e) {
// prevent the form from submitting
e.preventDefault();
// validate forms
let isUsernameValid = checkUsername(),
isEmailValid = checkEmail(),
isPasswordValid = checkPassword(),
isConfirmPasswordValid = checkConfirmPassword();
let isFormValid = isUsernameValid &&
isEmailValid &&
isPasswordValid &&
isConfirmPasswordValid;
// submit to the server if the form is valid
if (isFormValid) {
}
});
How it works:
•First, call each individual function to validate username, email, password, and
confirm password fields.
•Second, use the && operator to determine if the form is valid. The form is valid
only if all fields are valid.
•Finally, submit data to the server if the form is valid specified
the isFormValid flag. Note that submitting form data to the server isn’t covered in
this tutorial.
Now, you can open the index.html file, enter some values and click the submit button to
test it.
Add Instant feedback feature
The form only shows the error or success when you click the Sign Up button.
To provide instant feedback, you can attach an event listener to the input event of each
field and validate it.
It’s even better to use the event delegation so that you attach the input event listener to the
form and validate each field based on the current field id, like this:
form.addEventListener('input', function (e) {
switch (e.target.id) {
case 'username':
checkUsername();
break;
case 'email':
checkEmail();
break;
case 'password':
checkPassword();
break;
case 'confirm-password':
checkConfirmPassword();
break;
}
});
If you open the index.html and enter some data, you’ll see that the form shows the
feedback either error or success instantly.
Also, you improve the performance of the form by using the debouncing technique.
Technically, you’ll wait for the users to pause the typing for a small amount of time or
stop typing before validating the input.
For the detail of the debouncing technique, check it out in this tutorial.
The following illustrates the debounce() function:
const debounce = (fn, delay = 500) => {
let timeoutId;
return (...args) => {
// cancel the previous timer
if (timeoutId) {
clearTimeout(timeoutId);
}
// setup a new timer
timeoutId = setTimeout(() => {
fn.apply(null, args)
}, delay);
};
};
Now, you can pass the input event handler to the debounce() function to debounce it:
form.addEventListener('input', debounce(function (e) {
switch (e.target.id) {
case 'username':
checkUsername();
break;
case 'email':
checkEmail();
break;
case 'password':
checkPassword();
break;
case 'confirm-password':
checkConfirmPassword();
break;
}
}));
If you enter data to a form field to trigger the input event, you’ll see that the error or success
message will have a bit of delay.
The following shows the complete app.js file:
const usernameEl = document.querySelector('#username');
const emailEl = document.querySelector('#email');
const passwordEl = document.querySelector('#password');
const confirmPasswordEl = document.querySelector('#confirm-
password');
const form = document.querySelector('#signup');
const checkUsername = () => {
let valid = false;
const min = 3,
max = 25;
const username = usernameEl.value.trim();
if (!isRequired(username)) {
showError(usernameEl, 'Username cannot be blank.');
} else if (!isBetween(username.length, min, max)) {
showError(usernameEl, `Username must be between ${min}
and ${max} characters.`)
} else {
showSuccess(usernameEl);
valid = true;
}
return valid;
};
const checkEmail = () => {
let valid = false;
const email = emailEl.value.trim();
if (!isRequired(email)) {
showError(emailEl, 'Email cannot be blank.');
} else if (!isEmailValid(email)) {
showError(emailEl, 'Email is not valid.')
} else {
showSuccess(emailEl);
valid = true;
}
return valid;
};
const checkPassword = () => {
let valid = false;
const password = passwordEl.value.trim();
if (!isRequired(password)) {
showError(passwordEl, 'Password cannot be blank.');
} else if (!isPasswordSecure(password)) {
showError(passwordEl, 'Password must has at least 8
characters that include at least 1 lowercase character, 1
uppercase characters, 1 number, and 1 special character in (!@#$
%^&*)');
} else {
showSuccess(passwordEl);
valid = true;
}
return valid;
};
const checkConfirmPassword = () => {
let valid = false;
// check confirm password
const confirmPassword = confirmPasswordEl.value.trim();
const password = passwordEl.value.trim();
if (!isRequired(confirmPassword)) {
showError(confirmPasswordEl, 'Please enter the password
again');
} else if (password !== confirmPassword) {
showError(confirmPasswordEl, 'The password does not
match');
} else {
showSuccess(confirmPasswordEl);
valid = true;
}
return valid;
};
const isEmailValid = (email) => {
const re = /^(([^<>()\[\]\\.,;:\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,}))$/;
return re.test(email);
};
const isPasswordSecure = (password) => {
const re = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?
=.*[!@#\$%\^&\*])(?=.{8,})");
return re.test(password);
};
const isRequired = value => value === '' ? false : true;
const isBetween = (length, min, max) => length < min || length >
max ? false : true;
const showError = (input, message) => {
// get the form-field element
const formField = input.parentElement;
// add the error class
formField.classList.remove('success');
formField.classList.add('error');

// show the error message


const error = formField.querySelector('small');
error.textContent = message;
};
const showSuccess = (input) => {
// get the form-field element
const formField = input.parentElement;
// remove the error class
formField.classList.remove('error');
formField.classList.add('success');
// hide the error message
const error = formField.querySelector('small');
error.textContent = '';
}
form.addEventListener('submit', function (e) {
// prevent the form from submitting
e.preventDefault();
// validate fields
let isUsernameValid = checkUsername(),
isEmailValid = checkEmail(),
isPasswordValid = checkPassword(),
isConfirmPasswordValid = checkConfirmPassword();
let isFormValid = isUsernameValid &&
isEmailValid &&
isPasswordValid &&
isConfirmPasswordValid;
// submit to the server if the form is valid
if (isFormValid) {
}
});
const debounce = (fn, delay = 500) => {
let timeoutId;
return (...args) => {
// cancel the previous timer
if (timeoutId) {
clearTimeout(timeoutId);
}
// setup a new timer
timeoutId = setTimeout(() => {
fn.apply(null, args)
}, delay);
};
};
form.addEventListener('input', debounce(function (e) {
switch (e.target.id) {
case 'username':
checkUsername();
break;
case 'email':
checkEmail();
break;
case 'password':
checkPassword();
break;
case 'confirm-password':
checkConfirmPassword();
break;
}
}));

You might also like