How to validate phone number length and numeric values in JavaScript?

Summary

Phone number validation failed due to incorrect length check and numeric validation in JavaScript, causing invalid phone numbers to pass validation.

Root Cause

  • Incorrect length check: phone.length does not work on DOM elements; it should be phone.value.length.
  • Flawed numeric validation: !isNaN(phone) checks the element itself, not its value, and uses a bitwise AND (&) instead of logical AND (&&).

Why This Happens in Real Systems

  • Assumptions about DOM elements: Developers often mistakenly assume phone.length refers to the input value’s length.
  • Operator confusion: Mixing up & (bitwise) and && (logical) operators leads to unintended behavior.

Real-World Impact

  • Security risks: Invalid phone numbers can bypass validation, leading to potential fraud or system abuse.
  • Poor user experience: Users receive incorrect feedback, causing frustration and mistrust.

Example or Code

var loginBtn = document.querySelector('.login-btn');
var phone = document.getElementById('phone');

function validation() {
    if (phone.value.length === 11 && /^\d+$/.test(phone.value)) {
        window.alert("You are logged in");
    } else {
        window.alert("Phone is not valid!");
    }
}

How Senior Engineers Fix It

  • Use value property: Always access phone.value for input data.
  • Regex for numeric validation: /^\d+$/.test(phone.value) ensures all characters are digits.
  • Logical operators: Replace & with && for correct conditional evaluation.

Why Juniors Miss It

  • Lack of DOM understanding: Juniors may not fully grasp how DOM elements and their values differ.
  • Overlooking edge cases: Insufficient testing for non-numeric or incorrectly formatted inputs.
  • Operator ambiguity: Misinterpreting the purpose and behavior of & vs &&.

Leave a Comment