I have created a directive that restricts text input to only decimal numbers in the text field.
Below is the code for the directive:
import { HostListener, Directive, ElementRef } from '@angular/core';
@Directive({
exportAs: 'decimal-number-directive',
selector: 'decimal-number-directive, [decimal-number-directive]',
})
export class DecimalNumberDirective {
private regex: RegExp = new RegExp(/^\d*\.?\d{0,2}$/g);
private specialKeys: string[] = ['Backspace', 'Tab', 'End', 'Home'];
constructor(private el: ElementRef) {}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent): void {
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
const current: string = this.el.nativeElement.value;
const next: string = current.concat(event.key);
if (next && !String(next).match(this.regex)) {
event.preventDefault();
}
}
}
Here is an example of its usage:
<div class="col-2 pr-0">
<label>{{ l('Percent') }}</label>
<input
class="form-control"
type="text"
decimal-number-directive
name="percent"
[(ngModel)]="inquiryItemToAdd.percent"
maxlength="64"
(ngModelChange)="setTotalPrice()"
[readOnly]="!inquiryItemToAdd.servicePriceId || !servicePrice.isPriceCalculated"
/>
</div>
However, I am facing a challenge where I can still input values like 155.00 or 155.56. I aim to limit it to 100.00 as I am using this for writing percents.
I attempted to use the following regex
private regex: RegExp = new RegExp(/^(\d{1,2}(\.\d{1,2})?)|(100(\.0{1,2})?)$/g);
, but I am still able to input values exceeding 100 percent.
Any suggestions on how to solve this issue?