Explain Codes LogoExplain Codes Logo

Check if input is a number or letter in JavaScript

javascript
input-validation
type-coercion
regex-patterns
Nikita BarsukovbyNikita BarsukovΒ·Aug 25, 2024
⚑TLDR

In JavaScript, we can use regular expressions (regex) to verify if an input is a number or a letter:

let input = 'A'; // Ranch it up with your own user input, brotendo! let isNumber = /^\d+$/.test(input); // True if number, blast off to the moon πŸš€ let isLetter = /^[a-zA-Z]+$/.test(input); // True if letter, pew pew! console.log(isNumber ? 'Number' : isLetter ? 'Letter' : 'Other');

This hacky dacky snippet fires regex lasers ^\d+$ for numbers and ^[a-zA-Z]+$ for letters, thus compactly identifying the type of input.

Extended validation: Supercharge your user input checks

Fast answer got the basics down, but let's crank it to eleven and see some ninja-level validation!

Using type coercion for binary definitive analysis

JavaScript gets a little sneaky with type coercion. Use unary plus (+) to bykick to the face this trickiness, and convert input to a number prior to isNaN check:

function isNumeric(input) { return !isNaN(+input); // Unary plus for the win! πŸͺ‚ }

Validation on form submission - Because nobody likes spam

The real challenge is validating form submissions. The document.forms is a trusty ally here:

document.forms['myForm'].addEventListener('submit', function(event) { let input = this.elements['inputField'].value; if (isNaN(input) || input == '') { // Ah ah ah! You didn't say the magic word! 😠 alert('Please enter a valid number.'); event.preventDefault(); // Ninja vanish, prevent that form submission! πŸ•³ } });

Being super strict with regex - Because hygiene matters

Some tricky characters like periods (.) can be a bit of a bother, as they can pass as numeric due to decimal numbers. Well, it’s your call to accept them or not and adjust your regex accordingly:

let isFloat = /^\d*(\.\d+)?$/.test(input); // True if a valid floating-point number (We're floating in space, Dave. 🌌)

Regex denial - Because boundaries are healthy

Safe to assume some inputs should only be purely numeric. In that case, ensure the input is fully numeric with this strict regex pattern:

let isPureNumber = /^[\d]+$/.test(input); // Deny any sneaky non-digit characters (You shall not pass! πŸ§™β€β™‚οΈ)

Mastering Validation: Beyond basics

Rely on your friendly neighbourhood browser

Modern browsers are equipped with built-in validation to save the day! With a simple type="number" in your <input> fields, the browser will reject any non-numeric characters:

<input type="number" name="quantity" required>

Beware of empty strings

Empty strings can produce a false positive with isNaN(). A truthiness check along with isNaN() turns out to be a clever move:

let isEmpty = input == ''; let isNumeric = !isNaN(input) && input; // Truthiness check to the rescue! πŸ¦Έβ€β™‚οΈ

Your validation army - Multiple checks

Add more arsenals to your validation army by combining diverse checks to enhance your validation game:

function validateInput(input) { let isNumber = /^\d*(\.\d+)?$/.test(input); let isLetter = /^[a-zA-Z]+$/.test(input); let isEmpty = input == ''; if (isEmpty) { return 'Empty input. Not on my watch!'; // Who you gonna call? Empty string busters! πŸ‘» } else if (isNumber) { return 'Number'; } else if (isLetter) { return 'Letter'; } else { return 'No soup for you! Invalid input!'; // A Seinfeld reference never hurts 😊 } }

Real-time feedback for better user interaction

Implementing validation checks with event listeners on key presses or input changes provides a UX level up with real-time feedback:

document.getElementById('inputField').addEventListener('input', function() { let validationResult = validateInput(this.value); console.log(validationResult); // Update UI or do a victory dance πŸ’ƒ });