This is an HTML5 question but related to Angular.
I've been trying to prevent the input of more than one dot in a field with <input type="number">
inside an Angular form. I've tried:
- Directive in input element with keypress event to prevent multiple dots.
- Custom validator to raise an error when more than one dot it's present.
For now, I'm trying to prevent multiple dot/comma input with a directive applied to the input, removing dot/comma when there is already present a dot/comma or when the input value is an invalid number.
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[single-dot]'
})
export class SingleDotDirective {
private el: HTMLInputElement;
constructor(private elementRef: ElementRef) {
this.el = this.elementRef.nativeElement;
}
@HostListener('keypress', ['$event'])
onkeypress(event: KeyboardEvent): void {
const invalidInput = this.el.validity.badInput;
const inputCharSeparator =
String.fromCharCode(event.charCode) === '.' ||
String.fromCharCode(event.charCode) === ',';
const alreadyWithSeparator =
this.el.value.toString().indexOf('.') !== -1 ||
this.el.value.toString().indexOf(',') !== -1;
if (inputCharSeparator && (alreadyWithSeparator || invalidInput)) {
event.preventDefault();
}
}
}
But I found a problem, when I try to capture the current input value, the browser returns an empty string when the number is invalid. You can see the reason here: How to get the raw value an <input type="number"> field?
So for example, for a field like:
<input type="number" id="edQuantity">
edQuantity.value
will return:
"2.1"
if input number is2.1
""
if input number is2.
"2.1"
if input number is2,1
2
if input number is2,
If I check edQuantity.validity.badInput
for the last case I'm getting false
.
My code can't detect that the value of the input is bad when a comma is present, so you can input values like:
2,.22
So, my questions are:
- Why the validation result it's different for
,
? - What's the function of comma when present in field?
- Any idea to fix my code?
I've tested this in Chrome and Fx.
Thanks!