I am new on Stack overflow so please forgive me If I am wrong anywhere. I am stuck with the problem in Angular 6, I have few input fields of type number and text and I want to prevent users from entering any character other than '.' (dot) and only enter positive numbers with a single dot for eg. "1.22" and not "1..2." or "-1.12" or "-111".
I have tried (keyup), (keypress) and (keydown) but each of them works really confusing for me. Please advice if there is any directive or any solution. in html
<input type="number"(keyup)="numberOnlyWithDecimal($event,xyz)" name="weight [(ngModel)]="xyz" min="0" step="0.1"> in .ts
public textlength=0; numberOnlyWithDecimal(event, text): boolean { var regex = /^\d+(\.\d+)?$/; const charCode = (event.which) ? event.which : event.keyCode; var text2 = text + '' var test = text2.split(".") if (text2) { this.textlength = test.length-1 ; } if(text == null && charCode == 46){ return false; } if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) { return false; } if (!regex.test(charCode)) { return false } if (charCode === 46 && this.textlength ===1 ) { return false } return true; }