1

I have an Input element with type = "number", which is supposed to only accept 0,1,..,9 and "." Per default you can also wrie +, - ans soem other characters which I prevent with EventListener "keydown" and keyCodes. It works fine.

But how can I prevent the user from pasting or drag and dropping some other stuff into the input? I tried to validate input.value but it actually gives me "" when it is not a valid number. Is there a way to see what the user wants to paste, before it is pasted?

I also know, that I could change the type to "text", but at leas for now it is not an option.

Thanks.

2
  • You should be able to use the oninput to handle this. Commented Feb 14, 2019 at 15:39
  • 2
    use the pattern attribute to only accept 0-9. Use a min="0" to prevent negative numbers. Sure they can enter in invalid characters but the form will be invalid and prevent a submit Commented Feb 14, 2019 at 15:39

5 Answers 5

2

If you want to reject any input other than 0-9 and ., try this:

Array.from(document.getElementsByClassName('restricted')).forEach(elem => {
  elem.addEventListener('input', event => {
    event.target.value = event.target.value.replace(/[^0-9\.]/g, '');
  });
});
<input type="text" class="restricted">

You can add .restricted to any input to achieve the same effect once this script is in place. Unfortunately, this trick won’t work with input[type="number"], because event.target.value is '' whenever an invalid input state is detected.

Sign up to request clarification or add additional context in comments.

Comments

1

Without javascript

:invalid {
  color: red
}
<form method="post" action="https://httpbin.org/post">
  <input type="number" name="num" pattern="[0-9]*[.,]?[0-9]+" min="0" step="any">
  <!-- you won't be able to submit when the form is invalid -->
  <input type="submit">
</form>

PS (browser take care of normalizing the , to .)

Comments

0

I have countered something similar, i used regex to filter the entered value of any characters only accepts numbers. the down side to this solution is that it only accept integer numbers not numeric. here is a code example:

handleChange = (e) => {
    const re = /^[0-9\b]+$/;
    if (e.target.value === '' || re.test(e.target.value)) {
         this.setState({Number: e.target.value})
      }
  }

I'm using reactjs for this example, but of course you can adjust the code to serve your purpose

Comments

0

Use this:

It allows you to use any kind of input filter on a text , including various numeric filters. This will correctly handle Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, and all keyboard layouts.

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}
<input name="someid" onkeypress="return isNumberKey(event)"/>

6 Comments

How will either of those events help if someone just types the wrong number in, or wants to paste a correct one?
I add for "paste", too
Check, i fix it
No, you haven’t. I can still paste an invalid value into that input
What do you paste?
|
0

try this event:

Pasting:

https://developer.mozilla.org/en-US/docs/Web/Events/paste

Draging:

https://developer.mozilla.org/en-US/docs/Web/Events/drag

maybe look at this:

How do I make control characters programatically in Javascript?

EDIT:

document.getElementById('id').addEventListener('paste', (e) => {
  let pre = e.target.value;
  window.setTimeout(() => {
    console.log(pre);
    console.log(e.target.value);
    /*
    Get the pasted value here, and edit the input
    */
  });
});

2 Comments

How will either of those events help if someone just types the wrong number in, or wants to paste a correct one?
What if I just click in the text field and type +?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.