Revision on client side and server side validation
1. Using Javacsript
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
    let x = document.forms["myForm"]["fname"].value;
    if (x == "") {
        alert("Name must be filled out");
        return false;
</script>
</head>
<body>
<h2>JavaScript Validation</h2>
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
    Name: <input type="text" name="fname">
    <input type="submit" value="Submit">
</form>
</body>
</html>
   2. Using Bootstrap
<!DOCTYPE html>
<html lang="en">
<head>
 <title>Bootstrap Example</title>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
rel="stylesheet">
 <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container mt-3">
 <h3>Form Validation</h3>
 <p>Try to submit the form.</p>
 <form action="/action_page.php" class="was-validated">
  <div class="mb-3 mt-3">
   <label for="uname" class="form-label">Username:</label>
   <input type="text" class="form-control" id="uname" placeholder="Enter username" name="uname"
required>
   <div class="valid-feedback">Valid.</div>
   <div class="invalid-feedback">Please fill out this field.</div>
  </div>
  <div class="mb-3">
   <label for="pwd" class="form-label">Password:</label>
   <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pswd"
required>
   <div class="valid-feedback">Valid.</div>
   <div class="invalid-feedback">Please fill out this field.</div>
  </div>
  <div class="form-check mb-3">
   <input class="form-check-input" type="checkbox" id="myCheck" name="remember" required>
   <label class="form-check-label" for="myCheck">I agree on blabla.</label>
   <div class="valid-feedback">Valid.</div>
   <div class="invalid-feedback">Check this checkbox to continue.</div>
  </div>
 <button type="submit" class="btn btn-primary">Submit</button>
 </form>
</div>
</body>
</html>
                                     Revision on form
The first part of web programming course provides you with your very first experience of creating a web
form, including designing a simple form, implementing it using the right HTML form controls and other
HTML elements, adding some very simple styling via CSS, and describing how data is sent to a server.
Objective To gain familiarity with what web forms are, what they are used for, how to think about designing them,
:         and the basic HTML elements you'll need for simple cases.
What are web forms?
Web forms are one of the main points of interaction between a user and a website or application. Forms
allow users to enter data, which is generally sent to a web server for processing and storage or used on
the client-side to immediately update the interface in some way (for example, add another item to a list,
or show or hide a UI feature).
A web form's HTML is made up of one or more form controls (sometimes called widgets), plus some
additional elements to help structure the overall form — they are often referred to as HTML forms. The
controls can be single or multi-line text fields, dropdown boxes, buttons, checkboxes, or radio buttons,
and are mostly created using the <input> element, although there are some other elements to learn
about too.
Form controls can also be programmed to enforce specific formats or values to be entered (form
validation), and paired with text labels that describe their purpose to both sighted and visually impaired
users.
Designing your form
Designing forms is an important step when you are building a site or application. It's beyond the scope of
this article to cover the user experience of forms, but if you want to dig into that topic you should read
the following articles:
In this note, we will build a simple contact form. Let's make a rough sketch.
Our form will contain three text fields and one button. We are asking the user for their name, their email
and the message they want to send. Hitting the button will send their data to a web server.
Implementing our form HTML
We will use the following HTML elements: <form>, <label>, <input>, <textarea>, and <button>.
The <form> element
All forms start with a <form> element, like this:
<form action="/my-handling-form-page" method="post">…</form>
This element formally defines a form. It's a container element like a <section> or <footer> element, but
specifically for containing forms; it also supports some specific attributes to configure the way the form
behaves. All of its attributes are optional, but it's standard practice to always set at least
the action and method attributes:
       The action attribute defines the location (URL) where the form's collected data should be sent
        when it is submitted.
       The method attribute defines which HTTP method to send the data with (usually get or post).
For now, add the above <form> element into your HTML <body>.
The <label>, <input>, and <textarea> elements
Our contact form is not complex: the data entry portion contains three text fields, each with a
corresponding <label>:
        The input field for the name is a single-line text field.
        The input field for the email is an input of type email: a single-line text field that accepts only
        email addresses.
       The input field for the message is a <textarea>; a multiline text field.
In terms of HTML code we need something like the following to implement these form widgets:
<form action="/my-handling-form-page" method="post">
 <p>
  <label for="name">Name:</label>
  <input type="text" id="name" name="user_name" />
 </p>
 <p>
  <label for="mail">Email:</label>
  <input type="email" id="mail" name="user_email" />
 </p>
 <p>
  <label for="msg">Message:</label>
  <textarea id="msg" name="user_message"></textarea>
 </p>
</form>
Update your form code to look like the above.
The <p> elements are there to conveniently structure our code and make styling easier. For usability and
accessibility, we include an explicit label for each form control. Note the use of the for attribute on
all <label> elements, which takes as its value the id of the form control with which it is associated — this
is how you associate a form control with its label.
There is great benefit to doing this — it associates the label with the form control, enabling mouse,
trackpad, and touch device users to click on the label to activate the corresponding control, and it also
provides an accessible name for screen readers to read out to their users.
On the <input> element, the most important attribute is the type attribute. This attribute is extremely
important because it defines the way the <input> element appears and behaves.
In our simple example, we use the value text for the first input — the default value for this attribute. It
represents a basic single-line text field that accepts any kind of text input.
       For the second input, we use the value email, which defines a single-line text field that only
        accepts a well-formed email address. This turns a basic text field into a kind of "intelligent" field
        that will perform some validation checks on the data typed by the user. It also causes a more
        appropriate keyboard layout for entering email addresses (e.g. with an @ symbol by default) to
        appear on devices with dynamic keyboards, like smartphones.
       Last but not least, note the syntax of <input> vs. <textarea></textarea>. This is one of the
        oddities of HTML. The <input> tag is a void element, meaning that it doesn't need a closing
        tag. <textarea> is not a void element, meaning it should be closed with the proper ending tag.
        This has an impact on a specific feature of forms: the way you define the default value. To define
        the default value of an <input> element you have to use the value attribute like this:
<input type="text" value="by default this element is filled with this text" />
On the other hand, if you want to define a default value for a <textarea>, you put it between the opening
and closing tags of the <textarea> element, like this:
<textarea>
by default this element is filled with this text
</textarea>
The <button> element
The markup for our form is almost complete; we just need to add a button to allow the user to send, or
"submit", their data once they have filled out the form. This is done by using the <button> element; add
the following just above the closing </form> tag:
<p class="button">
 <button type="submit">Send your message</button>
</p>
The <button> element also accepts a type attribute — this accepts one of three values: submit, reset,
or button.
       A click on a submit button (the default value) sends the form's data to the web page defined by
        the action attribute of the <form> element.
       A click on a reset button resets all the form widgets to their default value immediately. From a
        UX point of view, this is considered bad practice, so you should avoid using this type of button
        unless you really have a good reason to include one.
       A click on a button button does nothing! That sounds silly, but it's amazingly useful for building
        custom buttons — you can define their chosen functionality with JavaScript.
Basic form styling
Now that you have finished writing your form's HTML code, try saving it and looking at it in a browser. At
the moment, you'll see that it looks rather ugly.
Forms are notoriously tricky to style nicely. It is beyond the scope of this lecture to teach you form styling
in detail, so for the moment we will just get you to add some CSS to make it look OK.
First of all, add a <style> element to your page, inside your HTML head. It should look like so:
<style>
</style>
Inside the style tags, add the following CSS:
body {
    /* Center the form on the page */
    text-align: center;
form {
    display: inline-block;
    /* Form outline */
    padding: 1em;
    border: 1px solid #ccc;
    border-radius: 1em;
p+p{
    margin-top: 1em;
label {
    /* Uniform size & alignment */
    display: inline-block;
    min-width: 90px;
    text-align: right;
}
input,
textarea {
    /* To make sure that all text fields have the same font settings
     By default, text areas have a monospace font */
    font: 1em sans-serif;
    /* Uniform text field size */
    width: 300px;
    box-sizing: border-box;
    /* Match form field borders */
    border: 1px solid #999;
input:focus,
textarea:focus {
    /* Set the outline width and style */
    outline-style: solid;
    /* To give a little highlight on active elements */
    outline-color: #000;
textarea {
    /* Align multiline text fields with their labels */
    vertical-align: top;
    /* Provide space to type some text */
    height: 5em;
}
.button {
    /* Align buttons with the text fields */
    padding-left: 90px; /* same size as the label elements */
button {
    /* This extra margin represent roughly the same space as the space
     between the labels and their text fields */
    margin-left: 0.5em;
Save and reload, and you'll see that your form should look much less ugly.
Sending form data to your web server
The last part, and perhaps the trickiest, is to handle form data on the server side. The <form> element
defines where and how to send the data thanks to the action and method attributes.
We provide a name attribute for each form control. The names are important on both the client- and
server-side; they tell the browser which name to give each piece of data and, on the server side, they let
the server handle each piece of data by name. The form data is sent to the server as name/value pairs.
To name the data in a form, you need to use the name attribute on each form widget that will collect a
specific piece of data. Let's look at some of our form code again:
<form action="/my-handling-form-page" method="post">
    <p>
     <label for="name">Name:</label>
     <input type="text" id="name" name="user_name" />
    </p>
    <p>
     <label for="mail">Email:</label>
     <input type="email" id="mail" name="user_email" />
    </p>
    <p>
     <label for="msg">Message:</label>
  <textarea id="msg" name="user_message"></textarea>
 </p>
</form>
In our example, the form will send 3 pieces of data named user_name, user_email, and user_message.
That data will be sent to the URL /my-handling-form-page using the HTTP POST method.
On the server side, the script at the URL /my-handling-form-page will receive the data as a list of 3
key/value items contained in the HTTP request. The way this script will handle that data is up to you.
Each server-side language (PHP, Python, Ruby, Java, C#, etc.) has its own mechanism of handling form
data.
JavaScript Control Structures: Mastering the Flow of Execution
In the realm of programming, the ability to control the flow of execution is paramount. JavaScript, a
ubiquitous language for web development, provides a rich set of control structures that empower
developers to orchestrate the sequence of actions their code performs. This comprehensive article
delves into the depths of JavaScript control structures, offering a thorough understanding of their
purpose, usage, and implications in modern web development.
1. Introduction
1.1 The Essence of Control Structures
Control structures are the building blocks of logical reasoning in programming. They dictate the order in
which instructions are executed, enabling programmers to create complex algorithms, handle
conditional scenarios, and implement loops for repetitive tasks. Without control structures, JavaScript
programs would simply run line by line, lacking the flexibility to adapt to dynamic situations.
1.3 Problem Solved and Opportunities Created
Control structures solve the fundamental problem of creating dynamic and interactive code. They enable
developers to:
        Respond to User Input: Control structures allow programs to react to user actions, such as
         button clicks or form submissions, providing a dynamic experience.
        Handle Errors and Exceptions: Control structures like try-catch blocks enable programs to
         gracefully handle errors, preventing crashes and ensuring a smoother user experience.
        Automate Repetitive Tasks: Loops allow for the efficient execution of tasks that need to be
         repeated a certain number of times or until a condition is met, saving time and effort.
       Build Complex Algorithms: Control structures enable the construction of complex algorithms by
        combining logical operations, creating efficient and robust code.
2. Key Concepts, Techniques, and Tools
2.1 The Building Blocks
JavaScript offers several core control structures, each with its own unique purpose and syntax:
2.1.1 Conditional Statements
       if Statement: Executes a block of code only if a specified condition is true.
       if (condition) { // Code to execute if condition is true }
       if-else Statement: Provides an alternative block of code to execute if the initial condition is false.
       if (condition) { // Code to execute if condition is true } else { // Code to execute if condition is
        false }
       if-else if-else Statement: Allows for multiple conditions to be evaluated sequentially.
       if (condition1) { // Code to execute if condition1 is true } else if (condition2) { // Code to execute
        if condition2 is true } else { // Code to execute if none of the above conditions are true }
       switch Statement: Evaluates an expression and matches it against a series of cases.
       switch (expression) { case value1: // Code to execute if expression matches value1 break; case
        value2: // Code to execute if expression matches value2 break; default: // Code to execute if no
        match is found }
2.1.2 Loops
       for Loop: Executes a block of code a specified number of times.
       for (initialization; condition; update) { // Code to execute }
       while Loop: Executes a block of code as long as a specified condition is true.
       while (condition) { // Code to execute }
       do-while Loop: Executes a block of code at least once, and then repeatedly as long as a specified
        condition is true.
       do { // Code to execute } while (condition);
       for-of Loop: Iterates over the elements of an iterable object, such as an array or string.
       for (const element of iterable) { // Code to execute for each element }
       for-in Loop: Iterates over the properties of an object.
       for (const property in object) { // Code to execute for each property }
2.1.3 Jump Statements
      break Statement: Exits the innermost loop or switch statement.
      for (let i = 0; i < 10; i++) { if (i === 5) { break; // Exit the loop when i equals 5 } }
      continue Statement: Skips the current iteration of a loop and moves to the next iteration.
      for (let i = 0; i < 10; i++) { if (i % 2 === 0) { continue; // Skip even numbers } console.log(i); }
      return Statement: Exits a function and optionally returns a value.
      function add(a, b) { return a + b; // Exit the function and return the sum }
2.2 Tools and Frameworks
While JavaScript control structures themselves are fundamental language features, various tools and
frameworks enhance their application in real-world development:
      Code Editors and IDEs: Modern code editors and integrated development environments (IDEs)
       like Visual Studio Code and WebStorm provide syntax highlighting, code completion, and
       debugging features that simplify working with control structures.
      Linters: Linters like ESLint help enforce coding style guidelines and detect potential issues related
       to control structure usage, promoting code quality and maintainability.
      Testing Frameworks: Frameworks like Jest and Mocha enable developers to write unit tests for
       functions and modules that involve control structures, ensuring code correctness and reliability.
      Debugging Tools: Browser developer tools and standalone debuggers allow developers to step
       through code execution line by line, inspecting variable values and analyzing the flow of control
       within their programs.
2.3 Current Trends and Emerging Technologies
The landscape of JavaScript development is constantly evolving. Here are some current trends and
emerging technologies that impact the use of control structures:
      Asynchronous Programming: With the rise of asynchronous programming, JavaScript developers
       increasingly rely on promises, async/await, and other techniques to manage code execution in a
       non-blocking manner. Control structures still play a vital role in managing the flow of
       asynchronous operations, especially when handling errors or coordinating multiple
       asynchronous tasks.
      Functional Programming: Functional programming paradigms emphasize immutability and side-
       effect-free functions. Control structures like map, filter, and reduce in JavaScript’s functional
       programming libraries (like Lodash) provide concise and efficient ways to manipulate data
       structures without mutating the original data.
      WebAssembly: WebAssembly, a low-level binary format that can be executed in web browsers,
       enables performance improvements for computationally intensive tasks. While WebAssembly
       itself doesn’t directly utilize JavaScript control structures, it can be called from JavaScript,
       leveraging JavaScript’s control structures to manage the execution of WebAssembly modules.
3.1 Real-World Applications
Control structures are indispensable for building interactive and dynamic web applications. Here are
some common use cases:
       Forms and User Input Validation: Control structures are used to validate user input, ensuring
        that data is entered correctly. For example, an if statement can check if a password field meets
        minimum length requirements, and a switch statement can handle different input types (e.g.,
        text, numbers, dates).
       Dynamic Content Display: Control structures enable the conditional display of content based on
        user preferences or server-side data. For example, an if statement can show different content
        based on the user’s logged-in status.
       Event Handling: Control structures are used to handle events like button clicks, mouse
        movements, and key presses. For example, an event listener can trigger a function that uses an if
        statement to determine which action to take based on the event type.
       Data Processing and Manipulation: Loops are essential for processing and manipulating data.
        For example, a for loop can iterate over an array of products and calculate their total price, or a
        for-of loop can extract specific information from an API response.
       Game Development: Control structures are fundamental in game development. For example,
        loops are used to update game logic, conditional statements are used to detect collisions, and
        switch statements can handle different game states.
3.2 Advantages and Benefits
Using control structures effectively provides several advantages:
       Code Reusability: Control structures allow developers to write concise and reusable code,
        eliminating redundancy and promoting maintainability.
       Flexibility and Adaptability: Control structures enable programs to adapt to changing conditions
        and user input, making applications more dynamic and user-friendly.
       Enhanced Logic and Decision-Making: Control structures provide the framework for
        implementing complex logical operations, enabling programs to make informed decisions based
        on data and conditions.
       Improved Efficiency: Loops and other control structures can streamline the execution of
        repetitive tasks, making code more efficient and reducing the amount of code required.
       Error Handling and Robustness: Control structures like try-catch blocks enhance code
        robustness by providing mechanisms for handling errors and preventing program crashes.
3.3 Industries Benefiting from Control Structures
Control structures are essential across various industries, where they power software applications of all
kinds. Here are a few examples:
       Web Development: Control structures are ubiquitous in web development, enabling the
        creation of dynamic websites, web applications, and user interfaces.
       Game Development: Control structures are fundamental in game development, controlling
        game logic, handling input, and managing game states.
       Mobile App Development: Control structures are essential for creating both native and hybrid
        mobile applications, enabling features like user interaction, data processing, and network
        communication.
       Data Science and Machine Learning: Control structures play a crucial role in data processing,
        analysis, and the implementation of machine learning algorithms.
       Cybersecurity: Control structures are used in cybersecurity tools to analyze network traffic,
        detect anomalies, and implement intrusion prevention systems.
4.1 Conditional Statements: A Practical Example
This example demonstrates how to use conditional statements to validate user input for a password
field:
function validatePassword(password) {
  if (password.length < 8) {
    return "Password must be at least 8 characters long.";
  } else if (!password.match(/[A-Z]/)) {
    return "Password must contain at least one uppercase letter.";
  } else if (!password.match(/[a-z]/)) {
    return "Password must contain at least one lowercase letter.";
  } else if (!password.match(/[0-9]/)) {
    return "Password must contain at least one number.";
  } else {
    return "Password is valid!";
  }
}
const passwordInput = document.getElementById("password");
const validationMessage = document.getElementById("validation-message");
passwordInput.addEventListener("blur", () => {
 const password = passwordInput.value;
 validationMessage.textContent = validatePassword(password);
});
4.2 Looping Through Data: A Practical Example
This example demonstrates how to use a for loop to iterate over an array of products and calculate their
total price:
const products = [
  { name: "Product A", price: 10.99 },
  { name: "Product B", price: 25.50 },
  { name: "Product C", price: 15.75 }
];
let totalPrice = 0;
for (let i = 0; i < products.length; i++) {
  totalPrice += products[i].price;
}
console.log("Total Price:", totalPrice);
7.1 Key Takeaways
        Control structures are essential for building dynamic and interactive web applications.
        JavaScript offers a variety of control structures, including conditional statements, loops, and
         jump statements.
        Control structures are used for validating user input, displaying dynamic content, handling
         events, and processing data.
        Effective use of control structures improves code readability, maintainability, and efficiency.
        Consider performance implications, especially in large-scale applications.
        Explore functional programming libraries and asynchronous programming techniques as
         alternatives to traditional control structures.