Explain Codes LogoExplain Codes Logo

Restricting input to textbox: allowing only numbers and decimal point

javascript
input-validation
real-time-validation
data-integrity
Anton ShumikhinbyAnton Shumikhin·Dec 12, 2024
TLDR

To enforce an HTML textbox to allow only numbers and a single decimal point, you can use JavaScript. Add an event listener for onkeydown which validates the following:

<input type="text" onkeydown="return event.key.match(/^[0-9.]$/) && !(/\./.test(this.value) && event.key === '.')">

This concise solution checks whether the pressed key is a valid number or the decimal point. It also ensures that an additional decimal point cannot be entered if one already exists. It's an efficient and straightforward approach that doesn't need auxiliary functions.

Expanded Solutions – Beyond Key Types

While our quick solution is great, its focus on single keystrokes means certain use cases are missed. To create a comprehensive solution, consider the following:

Real-Time validation with the 'oninput' event

To capture dynamic changes in the textbox, such as copy-pasting content or inputting autocorrect suggestions, add an oninput event listener:

<input type="text" oninput="limitDecimalPlaces(event)"> // Let's just say the decimal point walked into a bar, and the bartender said, "Sorry, we can't serve you. You keep on pushing your limit!" function limitDecimalPlaces(e) { const parts = e.target.value.split('.'); // Like a stern bar bouncer, the function ensures only up to 2 characters after the decimal. parts[1] = parts[1].substring(0, 2); e.target.value = parts.join('.'); }

By limiting the number of characters right after the decimal point, this method is handy for fields involving currencies.

Proactive Verification – The Power of Pre-Validation

Pre-validation helps maintain data integrity by inhibiting incorrect entries before they are rendered. This promotes seamless user experience and helps prevent confusion:

// Protip: Unsanitized inputs are like unrefrigerated leftovers. At one glance, everything might appear fine, but over time, they're bound to cause trouble. <input type="text" oninput="sanitizeInput(this)">

User Experience – Beyond Prevention

Preventing erroneous input is essential, but maintain a keen eye on offering informative feedback to users. Let them know what went wrong and how to fix it.

Subtle on-screen hints

You can add a onkeyup event to lightly shade the textbox border as the user types. This slight visual indicator is particularly useful for inhibitating disruptions in the user's concentration.

Explicit Error Messages

More importantly, as the user completes their input, use an onblur event to display a specific error message. This offers detailed information on the incorrect input, enhancing the overall user experience.

Submit Validation with Regex

Here's how you can form a last line of defense before the data is sent to the server:

// This form is like your grammar-obsessed English teacher in high school, won't let you submit your essay unless every comma, every period is in the right place! <form onsubmit="return validateFormOnSubmit(this)"> <input type="text" name="numericInput"> <input type="submit"> </form>

This technique ensures a thorough data integrity check, reinforcing a secure and error-free data transmission.