-1

I'm trying to create a textbox can accepts only digits while the user types in it.

I am talking about a live situation, I don't need to check it only at submitting.

To do that, I have added the following attribute to my textbox:

pattern="[0-9]*"

However, it doesn't work: I can still enter any kind of character like "a", "b" and not only "0", "1".

What is my fault here?

Thank you!

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<input class="input {{fields[$index].class}}" 
  ng-disabled="field.disabled != ''"  
  ng-required="field.name == zipcode"
  ng-model="fields[$index].value"
  name="{{field.name}}"
  type="text"
  id="{{field.name}}"
  maxlength="6"
  pattern="[0-9]*"
>
<label placeholder=" {{field.label}}">

</label>
tmighty
  • 10,734
  • 21
  • 104
  • 218
  • 6
    Patterns don't prevent you from typing non-pattern characters, they just determine form validity – Andy Ray May 01 '21 at 21:38
  • @AndyRay And how could I do what I need? – tmighty May 01 '21 at 21:40
  • With javascript... as the tag you chose would suggest we find in your question – Laurent S. May 01 '21 at 21:41
  • I have seen similar questions with a wide variety of solutions, and most with cave-ats. That's why I was looking for a clean solution that would work on all devices and all modern browers and with my current textbox. – tmighty May 01 '21 at 21:44
  • @ikiK Thank you, but I'm still too newbie for that. That's why I was hoping that this simply pattern would solve my problem without any further coding. – tmighty May 01 '21 at 21:45

1 Answers1

3

You can check the validity each time text is input.

let prevVal = "";
document.querySelector('input').addEventListener('input', function(e){
  if(this.checkValidity()){
    prevVal = this.value;
  } else {
    this.value = prevVal;
  }
});
<input maxlength="6" pattern="[0-9]*">

Learn more about validation here.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • Thank you. Do you think you could show me how to make it so that it only "responds" to this special textbox? I still have other textboxes which should allow other characters, too. In other words: Your solution is still to general for me. Can you show me to how wire it to my textbox? – tmighty May 01 '21 at 21:46
  • @tmighty You could give it an id and use `document.getElementById("yourId")` instead of `document.querySelector('input')`. – Unmitigated May 01 '21 at 21:47
  • Thank you. Can you show me what checkValidity would look like? – tmighty May 01 '21 at 21:53
  • 1
    @tmighty What do you mean? `checkValidity` is a built-in method on input elements. – Unmitigated May 01 '21 at 22:11