JAVASCRIPT

Validate String for Alphanumeric Characters (and optional spaces/hyphens)

Verify if a string contains only letters, numbers, spaces, and hyphens, commonly used for validating usernames or simple text inputs.

function isAlphanumericWithSpacesHyphens(inputString) {
    // Matches letters (a-z, A-Z), numbers (0-9), spaces (\s), and hyphens (-).
    // The `+` ensures at least one character. `^` and `$` anchor to start and end.
    const regex = /^[a-zA-Z0-9\s-]+$/;
    return regex.test(inputString);
}

console.log(isAlphanumericWithSpacesHyphens("hello-world 123")); // true
console.log(isAlphanumericWithSpacesHyphens("user_name"));       // false (contains underscore)
console.log(isAlphanumericWithSpacesHyphens("123abc"));          // true
console.log(isAlphanumericWithSpacesHyphens("!@#$"));            // false
How it works: The regex `^[a-zA-Z0-9\s-]+$` uses `^` and `$` to anchor the pattern to the beginning and end of the string, ensuring the *entire* string matches. `[a-zA-Z0-9\s-]` defines a character set that includes all uppercase and lowercase letters, digits, whitespace characters (`\s`), and hyphens. The `+` quantifier ensures there's at least one such character in the string, making it suitable for validating simple text fields like usernames or slugs.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs