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
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