Check if input is a number or letter in JavaScript
In JavaScript, we can use regular expressions (regex) to verify if an input is a number or a letter:
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:
Validation on form submission - Because nobody likes spam
The real challenge is validating form submissions. The document.forms
is a trusty ally here:
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:
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:
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:
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:
Your validation army - Multiple checks
Add more arsenals to your validation army by combining diverse checks to enhance your validation game:
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:
Was this article helpful?