DEV Community

Cover image for JavaScript Validation
Nzioki Dennis
Nzioki Dennis

Posted on

JavaScript Validation

We all have signed up/logged in to a site at one time. Also, probably we all have unintentionally left a field blank or even provided wrong data inputs which resulted in error logging in or even signing up. This is because the fields are validated. Data validation is the verification or checking that data provided in terms of correctness, accuracy against preset rules, formats or even constraints. This ensures data that is not compromised or corrupted into the system. JavaScript provides a way in which we can validate our data as it moves from client side to a web server.

Prerequisites: Basic Understanding of HTML, CSS and JavaScript
Objective: To understand well JavaScript Validation

Form Validation

Form validation is the process of making sure data provided by users into web forms meet the set criteria before being submitted to the server for the purpose of processing.

Types of Form Validation

  1. Client-Side Form Validation - Client-side form validation occurs within the user's browser using HTML, JavaScript, and sometimes HTML5 attributes. It provides real-time feedback to users while they fill out the form. This validation is user-friendly and reduces the number of unnecessary server requests. This is what we are looking at today.

  2. Server-Side Form Validation - Server-side form validation is performed on the server after data is submitted. It acts as a safety net to ensure that only valid data is processed. Server-side validation is critical for maintaining data consistency and security, as client-side validation can be bypassed.

Server-Side Form Validation

This kind of validation happens on the server side, where user input data is processed after being submitted through a form on a web page. Server-side validation is essential for maintaining data integrity, security, and consistency, regardless of whether client-side validation has been implemented. While client-side validation quickly tells users if their input is correct and helps avoid unnecessary trips to the server, it can be manipulated. On the other hand, server-side validation makes sure that only the right and real data goes into the website's backend so to speak. It's like having a gatekeeper on the website's side to double-check everything users submit. Languages commonly used to achieve in server-side validation are PHP, Ruby, Python and Java.

Client-Side Validation

Done using JavaScript and other scripting languages, Client-side validation is a process that validates user input on the browser before this data is submitted to the server. Immediate feedback is provided to the user on the status on the input, particularly with data entry errors.

Types of Client-Side Validation

a. Regular Expressions
Although not customizable like JavaScript, Regular expressions (regex) are a powerful tool for defining patterns in strings and record better performance. They are frequently employed to validate a variety of user inputs, including passwords, emails, and phone numbers. Regex offer a clear and adaptable approach to enforce particular forms or constraints for input data.

Example: Email Validation



const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (emailPattern.test(userInput)) {
    // Valid email format
} else {
    // Invalid email format
}


Enter fullscreen mode Exit fullscreen mode

b. HTML5 Form Validation
Using HTLM5 attributes we can perform validation without requiring JavaScript. This takes advantage of built-in attributes to enforce rules like pattern matching, min/max values and required values. Some key attributes include:

  • required: Specifies that a field must be filled out before submission.

  • type: Defines the expected input type (e.g., email, number, date).

  • pattern: Specifies a regular expression pattern for input validation.

Example: Using HTML5 Attributes



<input type="email" name="userEmail" required pattern="[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}">
<input type="number" name="userAge" min="18" max="99">


Enter fullscreen mode Exit fullscreen mode

c. JavaScript Validation
JavaScript validation allows developers to create customized JS functions which can be used to validate user inputs based on varied requirements.This gives developers an edge when it comes to control and flexibility when it comes to the whole validation process.

Example: Password Strength Check



function isStrongPassword(password) {
    // Custom validation logic to check password strength
}


Enter fullscreen mode Exit fullscreen mode

Getting Started

  • Open your editor (I use VS Code), create a folder and name it any name (lets call mine Validation)

  • Create three files: index.html, index.css and style.css

Should look like this:



Validation/
├── index.html
├── index.js
└── style.css


Enter fullscreen mode Exit fullscreen mode

Now we are going to create a signup form for an airline reservation system.

Creating the reservation form
Index.html:



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <title>Airliner Reservation Form</title>
</head>
<body>
    <div class="container">
        <h1>Reservations</h1>
        <form id="reservationForm">
            <label for="firstName">First Name:</label>
            <input type="text" id="firstName" name="firstName">

            <label for="lastName">Last Name:</label>
            <input type="text" id="lastName" name="lastName">

            <label for="email">Email:</label>
            <input type="email" id="email" name="email">

            <label for="reservationDate">Reservation Date:</label>
            <input type="date" id="reservationDate" name="reservationDate">

            <label for="phoneNumber">Phone Number:</label>
            <input type="tel" id="phoneNumber" name="phoneNumber">

            <label for="numTravelers">Number of Travelers:</label>
            <input type="number" id="numTravelers" name="numTravelers">

            <button type="submit">Submit</button>
        </form>
    </div>
    <script src="index.js"></script>
</body>
</html>


Enter fullscreen mode Exit fullscreen mode

This is how the page looks:

Reservation sign up

Styling the form
Styles.css:



body {
    margin: 0;
    padding: 0;
    font-family: Arial, sans-serif;
    background-image: url('plane.jpg'); /*replace this with the correct path to your image */
    background-size: cover;
}

.container {
    background-color: rgba(255, 255, 255, 0.8);
    padding: 20px;
    border-radius: 10px;
    margin: 50px auto;
    width: 300px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
}

h1 {
    text-align: center;
}

form {
    display: grid;
    gap: 7px;
}

label {
    font-weight: bold;
}

input {
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 4px;
}

button {
    padding: 10px;
    background-color: #3498db;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

button:hover {
    background-color: #2980b9;
}


Enter fullscreen mode Exit fullscreen mode

This is how the form looks after styling:

Styled form image

Validation
Something to note here, the validation is done on two levels; validating against blank fields (form inputs) and data formatting validation. Without any validation, the form submits data without checking the validity.
First lets see the behavior of our page without validation:

No validation

Validating against blank fields.



document.addEventListener('DOMContentLoaded', function() {
    const reservationForm = document.getElementById('reservationForm');

    reservationForm.addEventListener('submit', function(event) {
        // Prevent the form from submitting and refreshing the page
        event.preventDefault();

        // Get form inputs
        const firstName = document.getElementById('firstName').value;
        const lastName = document.getElementById('lastName').value;
        const email = document.getElementById('email').value;
        const reservationDate = document.getElementById('reservationDate').value;
        const phoneNumber = document.getElementById('phoneNumber').value;
        const numTravelers = document.getElementById('numTravelers').value;

        // Validate fields are not blank
        if (!firstName.trim()) {
            alert('Please enter your First Name.');
        } else if (!lastName.trim()) {
            alert('Please enter your Last Name.');
        } else if (!email.trim()) {
            alert('Please enter your Email.');
        } else if (!reservationDate.trim()) {
            alert('Please enter the Reservation Date.');
        } else if (!phoneNumber.trim()) {
            alert('Please enter your Phone Number.');
        } else if (!numTravelers.trim()) {
            alert('Please enter the Number of Travelers.');
        } else {
            // Move to the next section of validation
            performValidation(firstName, lastName, email, reservationDate, phoneNumber, numTravelers);
        }
    });
});


Enter fullscreen mode Exit fullscreen mode

Result would look like...

Blank field validation

Performing Validation on Correct Data Types



function performValidation(firstName, lastName, email, reservationDate, phoneNumber, numTravelers) {
    const currentDate = new Date();
    const selectedDate = new Date(reservationDate);

    // Validate data types and conditions
    if (!/^[a-zA-Z]+$/.test(firstName)) {
        alert('First Name should contain only characters.');
    } else if (!/^[a-zA-Z]+$/.test(lastName)) {
        alert('Last Name should contain only characters.');
    } else if (!/^\d{10}$/.test(phoneNumber)) {
        alert('Please enter a valid 10-digit Phone Number.');
    } else if (selectedDate < currentDate.setHours(0, 0, 0, 0)) {
        alert('Reservation Date must be today or in the future.');
    } else {
        alert('Reservation submitted successfully!');
        // Here you can send the form data to the server or perform other actions.
    }
}


Enter fullscreen mode Exit fullscreen mode

End result would look like...

Data validation

We can combine these two files and create one file, Index.js:



document.addEventListener('DOMContentLoaded', function() {
    const reservationForm = document.getElementById('reservationForm');

    reservationForm.addEventListener('submit', function(event) {
        // Prevent the form from submitting and refreshing the page
        event.preventDefault();

        // Get form inputs
        const firstName = document.getElementById('firstName').value;
        const lastName = document.getElementById('lastName').value;
        const email = document.getElementById('email').value;
        const reservationDate = document.getElementById('reservationDate').value;
        const phoneNumber = document.getElementById('phoneNumber').value;
        const numTravelers = document.getElementById('numTravelers').value;

        // Perform validation
        if (!firstName.trim()) {
            alert('Please enter your First Name.');
        } else if (!/^[a-zA-Z]+$/.test(firstName)) {
            alert('First Name should contain only characters.');
        } else if (!lastName.trim()) {
            alert('Please enter your Last Name.');
        } else if (!/^[a-zA-Z]+$/.test(lastName)) {
            alert('Last Name should contain only characters.');
        } else if (!email.trim()) {
            alert('Please enter your Email.');
        } else if (!reservationDate.trim()) {
            alert('Please enter the Travel Date.');
        } else {
            const currentDate = new Date();
            const selectedDate = new Date(reservationDate);

            // Allow the reservation to be made for today or a future date
            if (selectedDate < currentDate.setHours(0, 0, 0, 0)) {
                alert('Reservation Date must be today or in the future.');
            } else if (!phoneNumber.trim()) {
                alert('Please enter your Phone Number.');
            } else if (!/^\d{10}$/.test(phoneNumber)) {
                alert('Please enter a valid 10-digit Phone Number.');
            } else if (!numTravelers.trim()) {
                alert('Please enter the Number of Travelers.');
            } else {
                alert('Reservation submitted successfully!');
                // Here you can send the form data to the server or perform other actions.
            }
        }
    });
});


Enter fullscreen mode Exit fullscreen mode

There are few issues I feel like are largely ignored and would likely want to touch on:

Real-Time Feedback in JavaScript Form Validation

Real-time feedback is a strong web development approach that gives users immediate feedback as they interact with a web-based form. Real-time feedback informs users about the validity of their input as they write or make selections rather than waiting until the form is submitted to display validation alerts. This strategy improves the user experience by lessening annoyance and errors. Implementing real-time feedback in the context of JavaScript form validation entails dynamically reviewing the user's input and updating the interface as necessary. You may include real-time feedback into your form validation process by following these steps:

  • Input Event Listeners - Attach input event listeners to form fields (like text inputs, date pickers, etc.). These listeners monitor user input in real-time.

  • Immediate Validation - As users type or change values, trigger validation functions to check the input's validity. This can involve checking for correct data types, length requirements, and other criteria.

  • Updating UI Elements - Update the user interface elements (such as text messages, icons, or color changes) near the input field to provide immediate feedback. For example, you could display a green checkmark for valid input and a red warning symbol for invalid input.

  • Conditional Styling - Apply CSS classes dynamically to style the input fields based on their validation status. This can help users quickly identify valid and invalid inputs.

  • Conditional Enabling/Disabling - If you have buttons or actions dependent on valid input (like a "Submit" button), enable or disable them based on the input's validity status.

Here's are example code snippets demonstrating how real-time feedback can be added to a form input:
a. index.html:



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Real-Time Feedback Example</title>
</head>
<body>
    <div class="container">
        <h1>Real-Time Feedback Example</h1>
        <form id="reservationForm">
            <label for="firstName">First Name:</label>
            <input type="text" id="firstName" name="firstName" class="input-field">

            <!-- Other form fields... -->

            <button type="submit">Submit</button>
        </form>
        <p class="feedback-message" id="firstNameFeedback"></p>
    </div>
    <script src="index.js"></script>
</body>
</html>


Enter fullscreen mode Exit fullscreen mode

b. style.css



/* Your CSS styling... */

.input-field.invalid {
    border: 1px solid red;
}

.feedback-message {
    color: red;
}


Enter fullscreen mode Exit fullscreen mode

c. index.js:



document.addEventListener('DOMContentLoaded', function() {
    const firstNameInput = document.getElementById('firstName');
    const firstNameFeedback = document.getElementById('firstNameFeedback');

    firstNameInput.addEventListener('input', function() {
        const inputValue = firstNameInput.value.trim();

        if (!inputValue) {
            firstNameInput.classList.add('invalid');
            firstNameFeedback.textContent = 'Please enter your First Name.';
        } else {
            firstNameInput.classList.remove('invalid');
            firstNameFeedback.textContent = '';
        }
    });
});


Enter fullscreen mode Exit fullscreen mode

Output:

Real time validation

In this example, as the user types in their first name, the input's validation status is updated in real time. If the input is blank, a visual warning is displayed; otherwise, the warning is removed. By integrating real-time feedback, your form validation becomes more user-centric, helping users understand and correct errors as they occur, which contributes to an improved overall user experience.

Future Trends in JavaScript Form Validation:

  1. Web Components - Web components offer a modular and reusable way to encapsulate validation logic within custom elements. They promote code reusability and maintainability.

  2. Machine Learning and AI - Advanced techniques like machine learning and artificial intelligence can enhance form validation by predicting user input patterns, detecting anomalies, and providing more context-aware feedback.

  3. Smart Validation Libraries - Emerging validation libraries offer advanced features like fuzzy validation (tolerating minor input mistakes), semantic validation (understanding context), and automatic validation rule generation.

  4. Enhanced User Feedback - Future trends involve using rich UI elements like animations, interactive tooltips, and visual cues to provide more intuitive and user-friendly validation feedback.

  5. Integrated Linters and Editors - Integrated validation tools within code editors and IDEs can catch errors in real time during development, reducing the likelihood of deploying forms with validation issues.

  6. Accessibility - Future trends emphasize accessible validation feedback for users with disabilities. Providing meaningful error messages, using ARIA roles, and incorporating screen reader compatibility will become more important.

Wrap Up!
The complexity of JavaScript validation has been delved into in this article, revealing its diverse function in improving user experience and data integrity. Instant user response is made possible by client-side validation, speeding user interaction and reducing unnecessary server queries. While preserving data integrity, server-side validation demands efficient client-side process coordination. Real-time feedback adds a dynamic layer of responsiveness and gives users the ability to fix input mistakes as they happen. This in-depth comprehension highlights the value of carefully designed validation procedures, which ensure seamless user involvement, rigorous data validation, and ultimately the success of web applications in a technology-driven environment.

Happy Coding

Top comments (0)