I am currently developing a directive to validate an input:number field. The main objective of this field is to only accept numbers between 0-9 or a decimal number with up to 3 decimal places (ensuring that all numbers are positive without any symbols).
Since there are over 30 similar fields, I decided to create a directive to restrict users from entering unnecessary characters.
Below you will find the code for the directive as well as a Stackblitz example:
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" />
<!--These input fields are repeated multiple times throughout my code-->
The issue with the current code is that while it does allow only digits and decimal points, there are other problems arising such as:
- The maximum allowed length should be 7 digits, regardless of whether it is a decimal number. For instance: 1, 12, 1234567
- If it is a decimal number, then the maximum length should be 7 digits before the decimal and 3 digits after. For example: 1, 1.2, 1.12, 1.123
- It should not allow Backspacing (once limit reached) or moving the cursor.
- If the field is left blank without a default value