Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • PDF Invoice Generator
Menu

Javascript SweetAlert2 Example to Validate HTML5 Form Input Fields With Custom Icons & Messages

Posted on March 25, 2023

 

 

Welcome folks today in this blog post we will be implementing form validation in browser and also showing the custom icons and validation messages using the sweetalert2 library in javascript. All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to make an index.html file and copy paste the following code

 

 

index.html

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Form Validation Example</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.20/dist/sweetalert2.min.css">
</head>
<body>
    <h1>Form Validation Example</h1>
    <form id="form" novalidate>
        <label for="name">Name:</label>
        <input type="text" name="name" id="name">
        <br>
        <label for="email">Email:</label>
        <input type="email" name="email" id="email">
        <br>
        <button type="submit">Submit</button>
    </form>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.20/dist/sweetalert2.min.js"></script>
</body>
</html>

 

 

As you can see in the above html code we are including the cdn of the sweetalert2 library and also we have a simple html5 form where we have two input fields for taking the username and the email and then we have the submit button. And now we need to write the javascript code for the form validation as shown below

 

 

 

 

script.js

 

 

JavaScript
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
document.getElementById('form').onsubmit = (e) => {
            e.preventDefault()
            const name = document.getElementById('name').value;
            const email = document.getElementById('email').value;
            let errors = [];
 
            if (name.trim() === '') {
                errors.push('Please enter your name.');
            }
 
            if (email.trim() === '') {
                errors.push('Please enter your email address.');
            } else if (!isValidEmail(email)) {
                errors.push('Please enter a valid email address.');
            }
 
            if (errors.length > 0) {
                Swal.fire({
                    icon: 'error',
                    title: 'Validation Error',
                    text: errors.join('\n')
                });
                return false;
            }
 
            Swal.fire({
                icon: 'success',
                title: 'Form Submitted',
                text: 'Thank you for submitting the form!'
            });
  
            
        }
 
        function isValidEmail(email) {
            // A simple regular expression to validate email addresses
            const emailRegex = /^\S+@\S+\.\S+$/;
            return emailRegex.test(email);
        }

 

 

As you can see we are submitting the form and inside it we are getting the values submitted by the user and then we are validating the data such as username and the email address. And based upon that we are showing the sweetalert2 validation messages with icons as shown below

 

 

 

 

 

 

Recent Posts

  • Python 3 Flask Project to Export Multiple PDF Documents to Word Docx Files Using pdf2docx Library in Browser
  • Build a Fixed Deposit Interest Calculator Using Amount and Time in Browser Using HTML5 & Javascript
  • Python 3 Script to Convert PDF Document to Microsoft Word DOCX File Using pdf2docx Library
  • Node.js Express Project to Remove Background of Images Using Rembg & Formidable Library in Browser
  • Node.js Tutorial to Remove Background From Image Using Rembg & Sharp Library in Command Line
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme