Restrict zero at the first character only in angular 2+. (expected output- 10101)

Issue

How to restrict zero at the first character only in the input field (expected output is like 10101)?

This is my way of doing.

HTML markup:

<input type="text" class="form-control col-md-4" #check (keypress)="isInteger($event)">

Typescript .ts file:

@ViewChild("check") inputFileld:ElementRef;

isInteger(event)
{
    if(event.key=='0' && !this.inputFileld.nativeElement.value)
    {
       return false
    }
}  

With this trick, I’m not able to enter zero at first character but the problem is, write some number in the input field and select all the value and press zero that time zero is triggering.

Solution

HTML

<div>
      <input type="text" class="form-control col-md-4" #check  id="myText"   (keypress)="isInteger($event)">
    </div>

TS

isInteger(event) {

    var ctl = document.getElementById('myText');
    var startPos = ctl['selectionStart'];

    if (startPos == 0 && String.fromCharCode(event.which) == '0') {
      return false
    }
  }

Answered By – Rak2018

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.