Skip to main content

Input Validation in JavaScript

Overview

Input validation is a fundamental aspect of web development, ensuring user-provided data is correct and safe to process. This snippet demonstrates basic input validation in JavaScript, including checks for empty fields and validating email formats, enhancing the usability and security of web applications.

Code

Email validation function

function validateEmail(email) {
const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return emailRegex.test(email);
}

Non-empty field validation function

function validateNotEmpty(inputValue) {
return inputValue.trim() !== "";
}

Example Usage

Email validation

const userEmail = document.getElementById("emailInput").value;
if (validateEmail(userEmail)) {
console.log("The email is valid.");
} else {
alert("Please enter a valid email address.");
}

Non-empty field validation

const userName = document.getElementById("nameInput").value;
if (validateNotEmpty(userName)) {
console.log("The name is not empty.");
} else {
alert("Name cannot be empty.");
}

Code Description

The validateEmail and validateNotEmpty functions are JavaScript utilities designed for validating user input in web forms. Below is an overview of their functionalities:

validateEmail Function

  • Purpose: Validates whether an email address is in a valid format.
  • Implementation: Uses a regular expression (emailRegex) to define a valid email format and tests the input email against this pattern.
  • Return Value: Returns true if the email matches the pattern, false otherwise.

validateNotEmpty Function

  • Purpose: Checks if a text input is not empty or just whitespace.
  • Implementation: Trims the input value to remove leading and trailing whitespace and checks if the result is a non-empty string.
  • Return Value: Returns true if the input is non-empty, false otherwise.

These functions are essential for client-side form validation, ensuring that users provide necessary and correctly formatted data before submission.

References