Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)"/>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading