Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 105697
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T01:28:48+00:00 2026-05-11T01:28:48+00:00

Is there a quick way to set an HTML text input ( <input type=text

  • 0

Is there a quick way to set an HTML text input (<input type=text />) to only allow numeric keystrokes (plus ‘.’)?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-11T01:28:49+00:00Added an answer on May 11, 2026 at 1:28 am

    JavaScript

    You can filter the input values of a text <input> with the following setInputFilter function (supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, validity error message, and all browsers since IE 9):

    // Restricts input for the given textbox to the given inputFilter function. function setInputFilter(textbox, inputFilter, errMsg) {   [ "input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout" ].forEach(function(event) {     textbox.addEventListener(event, function(e) {       if (inputFilter(this.value)) {         // Accepted value.         if ([ "keydown", "mousedown", "focusout" ].indexOf(e.type) >= 0){           this.classList.remove("input-error");           this.setCustomValidity("");         }          this.oldValue = this.value;         this.oldSelectionStart = this.selectionStart;         this.oldSelectionEnd = this.selectionEnd;       }       else if (this.hasOwnProperty("oldValue")) {         // Rejected value: restore the previous one.         this.classList.add("input-error");         this.setCustomValidity(errMsg);         this.reportValidity();         this.value = this.oldValue;         this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);       }       else {         // Rejected value: nothing to restore.         this.value = "";       }     });   }); } 

    You can now use the setInputFilter function to install an input filter:

    setInputFilter(document.getElementById("myTextBox"), function(value) {   return /^\d*\.?\d*$/.test(value); // Allow digits and '.' only, using a RegExp. }, "Only digits and '.' are allowed"); 

    Apply your preferred style to the input-error class. Here’s a suggestion:

    .input-error{   outline: 1px solid red; } 

    Note that you still must do server side validation!

    Another caveat is that this will break the undo stack since it sets this.value directly. This means that CtrlZ will not work to undo inputs after typing an invalid character.

    Demo

    See the JSFiddle demo for more input filter examples or run the Stack snippet below:

    // Restricts input for the given textbox to the given inputFilter. function setInputFilter(textbox, inputFilter, errMsg) {   [ 'input', 'keydown', 'keyup', 'mousedown', 'mouseup', 'select', 'contextmenu', 'drop', 'focusout' ].forEach(function(event) {     textbox.addEventListener(event, function(e) {       if (inputFilter(this.value)) {         // Accepted value.         if ([ 'keydown', 'mousedown', 'focusout' ].indexOf(e.type) >= 0) {           this.classList.remove('input-error');           this.setCustomValidity('');         }                  this.oldValue = this.value;         this.oldSelectionStart = this.selectionStart;         this.oldSelectionEnd = this.selectionEnd;       }       else if (this.hasOwnProperty('oldValue')) {         // Rejected value: restore the previous one.         this.classList.add('input-error');         this.setCustomValidity(errMsg);         this.reportValidity();         this.value = this.oldValue;         this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);       }       else {         // Rejected value: nothing to restore.         this.value = '';       }     });   }); }  // Install input filters. setInputFilter(document.getElementById('intTextBox'), function(value) {   return /^-?\d*$/.test(value); }, 'Must be an integer'); setInputFilter(document.getElementById('uintTextBox'), function(value) {   return /^\d*$/.test(value); }, 'Must be an unsigned integer'); setInputFilter(document.getElementById('intLimitTextBox'), function(value) {   return /^\d*$/.test(value) && (value === '' || parseInt(value) <= 500); }, 'Must be between 0 and 500'); setInputFilter(document.getElementById('floatTextBox'), function(value) {   return /^-?\d*[.,]?\d*$/.test(value); }, 'Must be a floating (real) number'); setInputFilter(document.getElementById('currencyTextBox'), function(value) {   return /^-?\d*[.,]?\d{0,2}$/.test(value); }, 'Must be a currency value'); setInputFilter(document.getElementById('latinTextBox'), function(value) {   return /^[a-z]*$/i.test(value); }, 'Must use alphabetic latin characters'); setInputFilter(document.getElementById('hexTextBox'), function(value) {   return /^[0-9a-f]*$/i.test(value); }, 'Must use hexadecimal characters');
    .input-error {   outline: 1px solid red; }
    <h2>JavaScript input filter showcase</h2> <p>Supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, and <a href='https://caniuse.com/#feat=input-event' target='_blank'>all browsers since IE 9</a>.</p> <p>There is also a <a href='https://jsfiddle.net/emkey08/tvx5e7q3' target='_blank'>jQuery version</a> of this.</p> <table>   <tr>     <td>Integer</td>     <td><input id='intTextBox'></td>   </tr>   <tr>     <td>Integer &gt;= 0</td>     <td><input id='uintTextBox'></td>   </tr>   <tr>     <td>Integer &gt;= 0 and &lt;= 500</td>     <td><input id='intLimitTextBox'></td>   </tr>   <tr>     <td>Float (use . or , as decimal separator)</td>     <td><input id='floatTextBox'></td>   </tr>   <tr>     <td>Currency (at most two decimal places)</td>     <td><input id='currencyTextBox'></td>   </tr>   <tr>     <td>A-Z only</td>     <td><input id='latinTextBox'></td>   </tr>   <tr>     <td>Hexadecimal</td>     <td><input id='hexTextBox'></td>   </tr> </table>

    TypeScript

    Here is a TypeScript version of this.

    function setInputFilter(textbox: Element, inputFilter: (value: string) => boolean, errMsg: string): void {   ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout" ].forEach(function(event) {     textbox.addEventListener(event, function(this: (HTMLInputElement | HTMLTextAreaElement) & { oldValue: string; oldSelectionStart: number | null, oldSelectionEnd: number | null }) {       if (inputFilter(this.value)) {         this.oldValue = this.value;         this.oldSelectionStart = this.selectionStart;         this.oldSelectionEnd = this.selectionEnd;       }       else if (Object.prototype.hasOwnProperty.call(this, "oldValue")) {         this.value = this.oldValue;                  if (this.oldSelectionStart !== null &&           this.oldSelectionEnd !== null) {           this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);         }       }       else {         this.value = "";       }     });   }); } 

    jQuery

    There is also a jQuery version of this. See this answer.

    HTML5

    HTML5 has a native solution with <input type="number"> (see the specification and documentation). The documentation has a working demo of this input type.

    • Instead of reading the value property, read the valueAsNumber property of the input to get the typed value as a number rather than a string.
    • Usage inside a <form> is recommended because validation is made easier this way; for example, pressing Enter will automatically show an error message if the value is invalid.
      • You can use the checkValidity method or the requestSubmit method on the entire form in order to explicitly check the validity.
      • Note that you might need to use the required attribute in order to disallow an empty input.
    • You can use the checkValidity method or the validity property on the input element itself in order to explicitly check the validity.
    • You can use reportValidity to show an error message and use setCustomValidity to set your own message.

    This approach fundamentally has a different user experience: you are allowed to input invalid characters and the validation is performed separately. This has the benefit that the undo stack (CtrlZ) won’t break. Note that server-side validation must be performed, regardless, no matter which approach you choose.

    But note that browser support varies:

    • Most browsers will only validate the input when submitting the form, and not when typing.
    • Most mobile browsers don’t support the step, min and max attributes.
    • Chrome (version 71.0.3578.98) still allows the user to enter the characters e and E into the field. Also see the Q&A Why does the HTML input with type="number" allow the letter e to be entered in the field?.
    • Firefox (version 64.0) and Edge (EdgeHTML version 17.17134) still allow the user to enter any text into the field.

    Demo

    document.querySelector('form').addEventListener('submit', (event) => {   event.preventDefault();   console.log(`Submit!   Number is ${event.target.elements.number.valueAsNumber},   integer is ${event.target.elements.integer.valueAsNumber},   form data is ${JSON.stringify(Object.fromEntries(new FormData(event.target).entries()))}.`); })
    label {   display: block; }
    <form>   <fieldset>     <legend>Get a feel for the UX here:</legend>     <label>Enter any number: <input name='number' type='number' step='any' required></label>     <label>Enter any integer: <input name='integer' type='number' step='1' required></label>     <label>Submit: <input name='submitter' type='submit'></label>   </fieldset> </form>

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 87k
  • Answers 87k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Sigh. Never mind. Turns out it makes a difference if… May 11, 2026 at 5:37 pm
  • Editorial Team
    Editorial Team added an answer I use the httpfox Firefox extension to view all HTTP… May 11, 2026 at 5:37 pm
  • Editorial Team
    Editorial Team added an answer How to: Create a Project Template Using the Projectgen.exe Command-Line… May 11, 2026 at 5:37 pm

Related Questions

Say you have a legacy website running on an old code-base that offers certain
I want to use git to allow me to work on several features in
I have a file with a bunch of lines. I have recorded a macro
I have a long running insert transaction that inserts data into several related tables.

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.