JavaScript regex program to display name to be only numbers, letters and underscore.

In this article, we will learn the regex program to validate names to contain only numbers, letters, and underscores in JavaScript. Validating user input is essential for maintaining data integrity and security in web applications.

JavaScript Regex for Name Validation

Regular expressions (regex) are powerful tools for defining patterns to search and validate text. A common validation requirement is ensuring a name consists only of letters (A-Z, a-z), digits (0-9), and underscore (_).

To ensure that a name contains only allowed characters, we use the following regex pattern:

/^\w+$/

Regex Pattern Breakdown

  • ^: Start of the string
  • \w: Matches letters (A-Z, a-z), numbers (0-9), and underscores (_) only
  • +: Ensures at least one character
  • $: End of the string

This pattern ensures that no special characters, spaces, or symbols other than letters, numbers, and underscores are allowed.

Basic Regex Validation Example

Let's start with a simple console example to understand how the validation works:

function isValidName(name) {
    const regex = /^\w+$/;
    return regex.test(name);
}

// Test different inputs
console.log(isValidName("john_doe123"));    // true
console.log(isValidName("user-name"));      // false (hyphen not allowed)
console.log(isValidName("test name"));      // false (space not allowed)
console.log(isValidName("valid_123"));      // true
console.log(isValidName(""));              // false (empty string)
true
false
false
true
false

Web Form Implementation

Now let's implement this validation in a web form with real-time feedback:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Name Validation with Regex</title>
    <style>
        body {
            font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
            padding: 20px;
        }
        .result {
            font-size: 20px;
            font-weight: 500;
            margin: 10px 0;
        }
        .valid {
            color: green;
        }
        .invalid {
            color: red;
        }
        input[type="text"] {
            padding: 8px;
            font-size: 16px;
            margin: 10px 5px;
        }
        button {
            padding: 8px 15px;
            font-size: 16px;
            background-color: #007bff;
            color: white;
            border: none;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h1>Name Validation: Numbers, Letters and Underscore Only</h1>
    
    <div>
        <input type="text" class="nameInput" placeholder="Enter name (e.g., john_doe123)">
        <button class="checkBtn">CHECK</button>
    </div>
    
    <div class="result"></div>
    
    <h3>Valid examples: user123, john_doe, test_123</h3>
    <h3>Invalid examples: user-name, test name, @user</h3>

    <script>
        const resultElement = document.querySelector(".result");
        const nameInput = document.querySelector(".nameInput");
        const checkButton = document.querySelector(".checkBtn");

        function validateName() {
            const inputValue = nameInput.value;
            const regex = /^\w+$/;
            
            if (inputValue === "") {
                resultElement.innerHTML = "Please enter a name to validate";
                resultElement.className = "result";
                return;
            }
            
            if (regex.test(inputValue)) {
                resultElement.innerHTML = "? Valid name: Contains only letters, numbers, and underscores";
                resultElement.className = "result valid";
            } else {
                resultElement.innerHTML = "? Invalid name: Use only letters, numbers, and underscores";
                resultElement.className = "result invalid";
            }
        }

        checkButton.addEventListener("click", validateName);
        
        // Real-time validation on input
        nameInput.addEventListener("input", validateName);
    </script>
</body>
</html>

Key Methods Used

The document.querySelector() selects the first element that matches a specified CSS selector:

let resultElement = document.querySelector(".result");

The addEventListener() attaches an event handler to an element:

element.addEventListener("click", functionName);

The test() method tests a string against a regular expression pattern and returns true/false:

const isValid = regex.test(inputString);

Alternative Validation Approaches

Method Syntax Returns Use Case
test() regex.test(string) Boolean Simple validation
match() string.match(regex) Array or null Get matched parts
search() string.search(regex) Index or -1 Find position

Common Validation Scenarios

const nameRegex = /^\w+$/;

// Test various inputs
const testCases = [
    "john_doe",      // Valid
    "user123",       // Valid  
    "test_user_1",   // Valid
    "user name",     // Invalid (space)
    "user-name",     // Invalid (hyphen)
    "user@domain",   // Invalid (@ symbol)
    "123user",       // Valid (starts with number)
    "_user",         // Valid (starts with underscore)
];

testCases.forEach(name => {
    const isValid = nameRegex.test(name);
    console.log(`"${name}": ${isValid ? "Valid" : "Invalid"}`);
});
"john_doe": Valid
"user123": Valid
"test_user_1": Valid
"user name": Invalid
"user-name": Invalid
"user@domain": Invalid
"123user": Valid
"_user": Valid

Conclusion

Using JavaScript regex with the /^\w+$/ pattern provides a simple and effective way to validate names containing only letters, numbers, and underscores. The test() method offers the most efficient approach for boolean validation, ensuring data integrity in web applications.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2026-03-15T23:18:59+05:30

755 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements