Home > Net >  how can I make an input field only accept numbers when the input type is text?
how can I make an input field only accept numbers when the input type is text?

Time:01-31

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" 
       
      formControlName="idCardInput" 
      name="idCard" 
      id="idCard" 
      ng-pattern="/^[0-9]*$/" />

CodePudding user response:

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)"/>

CodePudding user response:

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

CodePudding user response:

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/app.component.html

  • Related