1

How can i restrict textbox that should only accept numbers and should not accept decimal values and alphabets?

Waqas Ali
  • 116
  • 8
  • Does this answer your question? [HTML text input allow only numeric input](https://stackoverflow.com/questions/469357/html-text-input-allow-only-numeric-input) – Mahatmasamatman Mar 05 '20 at 12:32
  • If your browsers support it, look into `` instead of `` to get a lot of the validation you'll want out of the box. – Shilly Mar 05 '20 at 12:35
  • number do allow decimal value. – Amit Chauhan Mar 05 '20 at 13:20
  • Better to add some more information about your question such as is it about web page, HTML or mobile platform so that others can help you better. – nngeek Mar 05 '20 at 14:36

2 Answers2

1

@shilly is correct you can use type="number" but if that doesn't work you can look into regex and create patterns based on what you want the input to look like.

Regex example for only numbers excluding decimal and letters: "^[0-9]+$"

1

first you need to create an input element which call a function

<input type = "text" id = "a" onkeyup="myFunction(event)"/>

now you define your input box which will call a function myFunction (which takes event) whenever you will press a key on your keyboard.

now we need to prevent all the other key except 0-9 and without (.) becuase you don't want any decimal point.

so we need to create a regex which can check the pattern and check if the typed value follows the pattern or not if it follow we will set the value in a variable if not then we will set input value to old correct value and call preventDefault.

<script>
let value = null;
function myFunction(event) {

    // event.target.value = what ever you typed
    // /^[0-9]+$/ = regex code to prevent other letter except 0123456789

    if (event.target.value.match(/^[0-9]+$/)) {
        value = event.target.value;
    } else {
        // this line will update your input box to correct value
        document.getElementById("a").value = value;
        event.preventDefault();
    }
}
</script>
Amit Chauhan
  • 1,810
  • 3
  • 17
  • 25