1

Here's my input field with label as ID, I want this input field to only accept numbers without changing the type to number.

<label for="id">ID:</label>
<input type="text" 
      class="form-control form-control-sm" 
      formControlName="idCardInput" 
      name="idCard" 
      id="idCard" 
      ng-pattern="/^[0-9]*$/" />
adiga
  • 34,372
  • 9
  • 61
  • 83
Haris
  • 83
  • 5
  • it's a bit old but, https://stackoverflow.com/questions/64163661/i-want-to-restrict-input-type-text-only-alphanumeric-in-angular-9-globally/64167098#64167098 – Eliseo Jan 30 '23 at 10:12
  • You can not prevent users from typing anything else than numbers in an input. For once the letter `E` is a valid number expression. Second, a User can always break it. That's why you should run a plausibility test and a validation and warn the user if the input is invalid. – tacoshy Jan 30 '23 at 10:12
  • ngx-mask is one viable option if you're willing to reach for a library option – Andrew Allen Jan 30 '23 at 10:14
  • @tacoshy, impossible is nothing. – Eliseo Jan 30 '23 at 10:39

3 Answers3

0

Using Javascript, you can use this function whenever you want inside your particular project or website.

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

If validating is not enough, and you want to accept only numeric chars inside the input field:

You can either use a function to test the input value on change and then to replace it, either way you should use a regex:

  1. /^\d+$/
  2. /^[0-9]*$/

Both options are fine

Since you are using angular you can use the (change) event and to call a function that will adjust the form control's value which is bind to the input.

You can also do it on the input itself using the oninput event together with this.value

SwissCodeMen
  • 4,222
  • 8
  • 24
  • 34
  • you should not just replace an input based on a regex. It makes up for poor UX and Accessibility. You should always warn a user instead! – tacoshy Jan 30 '23 at 10:26
-1

You need to create numbersOnly directive and then use it in your html. Use the following stackblitz link for reference:

https://stackblitz.com/edit/angular-numbers-only-directive?file=app%2Fapp.component.html