I am trying to validate a input:number field using directive. The purpose of the field is to accept only numbers between 0-9 or a decimal number up to 3 decimal places (numbers will be positive all time without any symbols).
As there are same type of fields of more than 30 so thought of creating a directive that will prevent users from entering unnecessary characters.
Below is my code for the same along with a Stackblitz sample:
Directive:
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[validTestValue]'
})
export class NumberDirective {
@HostListener('keydown', ['$event'])
@HostListener('input', ['$event'])
onKeyDown(e) {
const key = ['Backspace', 'Delete', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.'];
let check = key.includes(e.key) && /^\d{1,7}((.)|(.\d{0,3})?)$/.test(e.target.value);
console.log(check)
if (!check) {
e.preventDefault();
}
}
}
HTML:
<input type="number" validTestValue class="testInput-field text-center" />
<!--Same input fields are there many times in my code-->
The problem with this code is that I can enter value as I desired i.e. only digits and the decimal point is accepted but few other issues are arising like below:
- Excepted result should be max 7 digits whether or not it is a decimal number. Example: 1, 12, 1234567
- If decimal number then max 7 digits before decimal and max 3 digits after decimal. Example: 1, 1.2, 1.12, 1.123
- Cannot Backspace (if length reached) or move cursor.
- If the field is blank without any default value