How To Create Simple Validation With JavaScript And SweetAlert 2

In the rapidly advancing world of web development, JavaScript has become an indispensable programming language for creating engaging interactive experiences for users. However, the increasing complexity of web applications today makes data validation a crucial aspect in ensuring the integrity and security of user-inputted information.

JavaScript validation has become one of the most common and effective ways to ensure that data entered by users conforms to the expected format. In this article, the author will discuss the importance of JavaScript validation and how SweetAlert, a custom pop up library, can provide user-friendly interactions when validation fails.

We will create simple validations, such as ensuring that input fields like username and password must not be empty. In this tutorial, the author strives to make the validation code as simple as possible, yet provides well solvable solutions if you are looking for uncomplicated code.

JavaScript Form Validation

JavaScript form validation is the process of checking data entered by users in a form to ensure that it conforms to the expected format and rules before being sent to the server or further processed. Form validation is crucial in web development because it has several important benefits and objectives. Here is an explanation of the importance of form validation in JavaScript:

  • Preventing Incorrect or Dangerous Data Submission: Form validation helps prevent the submission of incorrect or dangerous data to the server. By confirming that the data entered by users is valid, we can avoid errors that could cause issues in the database or disrupt the application.
  • Enhancing Application Security: Form validation enhances application security by mitigating the risk of code injection or other attacks. For instance, validation on text inputs prevents users from inserting malicious scripts or HTML tags that could lead to XSS (Cross-Site Scripting) or other attacks.
  • Improving User Experience: Form validation provides quick and clear feedback to users about their input errors. Informative and visually appealing error messages, such as using SweetAlert, can help users understand and rectify their mistakes easily, thereby enhancing their overall experience while using the application.
  • Saving Time and Server Resources: By performing validation on the client-side (JavaScript), invalid data can be detected before being sent to the server. This reduces the server load since only valid data is forwarded for processing. Users also do not have to wait for server responses to find out about input errors.
  • Enhancing Data Quality: Form validation helps ensure that the data entered into the database or information system is consistent and compliant with the established rules. This ensures better data quality and reduces the likelihood of duplicate or irrelevant data.
  • Minimizing Human Errors: By providing guidance and validation in the form, human errors in data entry can be minimized. For example, when users are asked to enter a phone number, validation can ensure that only numbers are accepted and not other characters like letters or symbols.
  • Supporting Cross-Platform Compatibility: Form validation on the client-side using JavaScript enables users from various devices, such as desktops or mobile devices, to receive instant feedback about the validity of their data without relying on form submission to the server first.
  • By implementing form validation in JavaScript, we can improve the quality and security of web applications, reduce errors and inefficient resource usage, and provide users with a better and more responsive user experience.

SweetAlert 2

SweetAlert 2 is a JavaScript library used to create attractive, elegant, and easily customizable pop ups. This library is very popular as it can replace the native pop up functions of browsers with more appealing visuals and various customizable styles and animations. By using SweetAlert, developers can easily create pop up messages for various purposes, such as error messages, user action confirmations, success notifications, and more.

These messages can be presented with visually appealing layouts and equipped with customizable buttons to handle user responses. SweetAlert provides a more interactive and enjoyable experience for users, thereby enhancing the quality and aesthetics of the developed web applications. Official sweetalert 2 website https://sweetalert2.github.io/.

Tutorial

  1. First, to start the tutorial create a folder named sweetalert-js to facilitate our tutorial.
  2. Use your respective IDE according to your preference.
  3. Create file login.html and save into sweetalert-js folder. Here is the code :
  4. <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Login</title>
        <link
          href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"
          rel="stylesheet"
          integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65"
          crossorigin="anonymous"
        />
        <link
          rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css"
        />
    
        <!-- CDN sweetalert -->
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
        <style>
          body {
            background-color: white;
          }
    
          a {
            text-decoration: none;
          }
        </style>
      </head>
    
      <body>
        <!-- Section -->
        <section class="vh-100">
          <!-- Container -->
          <div class="container h-100">
            <!-- Row -->
            <div class="row d-flex justify-content-center align-items-center h-100">
              <!-- Col -->
              <div class="col-12 col-md-8 col-lg-6 col-xl-5 mt-4">
                <!-- Card -->
                <div
                  class="card shadow-lg p-3 mb-5 bg-body rounded"
                  style="border: 2px solid white"
                >
                  <!-- Card body -->
                  <div class="card-body p-5">
                    <!-- Icon login -->
                    <div class="mb-5 text-center">
                      <i class="bi bi-person-circle" style="font-size: 40px"></i>
                    </div>
                    <!-- </End icon login -->
    
                    <!-- Form -->
                    <form method="post" action="">
                      <!-- Username -->
                      <div class="mb-4">
                        <label class="form-label" for="username">Username</label>
                        <input
                          type="text"
                          id="username"
                          class="form-control"
                          name="username"
                          autocomplete="off"
                        />
                      </div>
                      <!-- </End username -->
    
                      <!-- Password -->
                      <div class="mb-4">
                        <label class="form-label" for="password">Password</label>
                        <input
                          type="password"
                          id="password"
                          class="form-control"
                          name="password"
                        />
                      </div>
                      <!-- </End password -->
    
                      <!-- Button login -->
                      <div class="text-center">
                        <button
                          class="btn btn-dark w-75 text-center rounded-pill"
                          type="submit"
                          name="login"
                        >
                          Login
                        </button>
                      </div>
                      <!-- </End button login -->
                    </form>
                    <!-- </End form -->
    
                    <!-- Line -->
                    <hr class="my-4" />
                    <!-- </End line -->
                  </div>
                  <!-- </End card body -->
                </div>
                <!-- </End card -->
              </div>
              <!-- </End col -->
            </div>
            <!-- </End row -->
          </div>
          <!-- </End container -->
        </section>
        <!-- </End section -->
    
        <script
          src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"
          integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4"
          crossorigin="anonymous"
        ></script>
       <script src="script.js"></script>
      </body>
    </html>

    I think you are already familiar with Bootstrap. However, if you are not familiar with Bootstrap, it's okay. You can simply copy the JavaScript code later and implement it according to your needs. The author intentionally used the pre made template above to create a visually appealing form UI. It's okay if you are not familiar with bootstrap the author will guide you step by step in understanding the JavaScript code implementation according to your needs.

  5. Result, if you open the login.html file :
  6. Now create file script.js and save into sweetalert-js. Here is the code :
  7. let username = document.getElementById('username');
    let password = document.getElementById('password');
    let formSubmit = document.getElementsByTagName('form')[0];
    
    formSubmit.addEventListener('submit', function(e) {
      if (username.value === "" && password.value === "") {
        e.preventDefault();
        Swal.fire(
          'Not Valid',
          'Username and password cannot be blank!',
          'error'
        );
      } else if (username.value === "") {
        e.preventDefault();
        Swal.fire(
          'Not Valid',
          'Username cannot be blank!',
          'error'
        );
      } else if (password.value === "") {
        e.preventDefault();
        Swal.fire(
          'Not Valid',
          'Password cannot be blank!',
          'error'
        );
      }
    });

    Here's the explanation step by step for the JavaScript code above:

    Obtaining References To Form Elements:
    let username = document.getElementById('username');
    let password = document.getElementById('password');
    let formSubmit = document.getElementsByTagName('form')[0];

    - In this step, we obtain references to the elements on the HTML page. document.getElementById('name_id') is used to get elements with specific ids. Here, elements with ids "username" and "password" are stored in the variables username and password, respectively.

    - Additionally, we use document.getElementsByTagName('name_tag') to get the first form element on the page (index 0) and store it in the variable formSubmit.

    Adding An Event Listener To The Form:
    formSubmit.addEventListener('submit', function(e) {

    - In this step, we add an event listener to the form element obtained earlier. The event listener is added for the "submit" event, which will be triggered when the user submits the form by pressing the submit button or through other actions that result in form submission.

    Form Validation:
    if (username.value === "" && password.value === "") {
      e.preventDefault();
      Swal.fire(
        'Not Valid',
        'Username and password cannot be blank!',
        'error'
      );
    }

    - Here, we check if both the "username" and "password" fields are empty using the if condition. username.value === "" checks if the value entered by the user in the "username" field is an empty string.

    - password.value === "" performs a similar check for the "password" field.

    - If both fields are empty, the code inside the if block is executed. e.preventDefault(); prevents form submission to the server by stopping the "submit" event. This is done to avoid submitting the form with invalid data.

    - Swal.fire() displays a SweetAlert with an error message. The message includes the title "Not Valid" and the content "Username and password cannot be blank!" with the popup type set to "error".

    Handling Specific Cases:
    } else if (username.value === "") {
      e.preventDefault();
      Swal.fire(
        'Not Valid',
        'Username cannot be blank!',
        'error'
      );
    } else if (password.value === "") {
      e.preventDefault();
      Swal.fire(
        'Not Valid',
        'Password cannot be blank!',
        'error'
      );
    }

    - After the validation for both empty fields, this code handles two specific cases related to the "username" and "password" fields separately.

    - If the "username" field is empty (username.value === ""), the code inside the first else if block is executed.

    - e.preventDefault(); prevents form submission to the server.

    - Swal.fire() displays a SweetAlert with a different error message: the title "Not Valid" and the content "Username cannot be blank!" with the popup type set to "error".

    - If the "password" field is empty (password.value === ""), the code inside the next else if block is executed, following the same steps as mentioned above.

    Closing The Event Listener:
    });

    - The event listener is closed with a closing curly brace (}) and a closing parentheses (); this indicates the end of the callback function that runs when the "submit" event occurs.

    With the provided code, form validation ensures that both the "username" and "password" fields must not be empty. If any of the fields are empty, the corresponding error message will be displayed using SweetAlert, and form submission will be prevented to avoid submitting invalid data to the server.

  8. All results :
  9. Done.

Closing

I hope you enjoy this tutorial and it helps you enhance your knowledge in JavaScript.