简体   繁体   中英

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

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]*$/" />

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM