Angular2 - Input Field to Accept Only Numbers

Numbers only Input in Angular

Look your regexp is correct and when you console the value in onChange the value is correct. The only problem is that it doesn’t display correctly, I tried to manually update it manually with DetectionRef.detectChanges but it did not help. I did what you need but in little different way please look on .html and directive
https://stackblitz.com/edit/angular-numbers-only-directive-xttsje

Angular 8 Input validation accept only numbers

You can create a custom directive for only number.
Stackblitz Demo

app.component.html

<input type="text" appOnlynumber/>

onlynumber.directive.ts

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
selector: '[appOnlynumber]'
})
export class OnlynumberDirective {

private navigationKeys = [
'Backspace',
'Delete',
'Tab',
'Escape',
'Enter',
'Home',
'End',
'ArrowLeft',
'ArrowRight',
'Clear',
'Copy',
'Paste'
];
inputElement: HTMLElement;
constructor(public el: ElementRef) {
this.inputElement = el.nativeElement;
}

@HostListener('keydown', ['$event'])
onKeyDown(e: KeyboardEvent) {
if (
this.navigationKeys.indexOf(e.key) > -1 || // Allow: navigation keys: backspace, delete, arrows etc.
(e.key === 'a' && e.ctrlKey === true) || // Allow: Ctrl+A
(e.key === 'c' && e.ctrlKey === true) || // Allow: Ctrl+C
(e.key === 'v' && e.ctrlKey === true) || // Allow: Ctrl+V
(e.key === 'x' && e.ctrlKey === true) || // Allow: Ctrl+X
(e.key === 'a' && e.metaKey === true) || // Allow: Cmd+A (Mac)
(e.key === 'c' && e.metaKey === true) || // Allow: Cmd+C (Mac)
(e.key === 'v' && e.metaKey === true) || // Allow: Cmd+V (Mac)
(e.key === 'x' && e.metaKey === true) // Allow: Cmd+X (Mac)
) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if (
(e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) &&
(e.keyCode < 96 || e.keyCode > 105)
) {
e.preventDefault();
}
}

@HostListener('paste', ['$event'])
onPaste(event: ClipboardEvent) {
event.preventDefault();
const pastedInput: string = event.clipboardData
.getData('text/plain')
.replace(/\D/g, ''); // get a digit-only string
document.execCommand('insertText', false, pastedInput);
}

@HostListener('drop', ['$event'])
onDrop(event: DragEvent) {
event.preventDefault();
const textData = event.dataTransfer.getData('text').replace(/\D/g, '');
this.inputElement.focus();
document.execCommand('insertText', false, textData);
}


}

How do I restrict an input to only accept numbers?

Easy way, use type="number" if it works for your use case:

<input type="number" ng-model="myText" name="inputName">

Another easy way:
ng-pattern can also be used to define a regex that will limit what is allowed in the field. See also the "cookbook" page about forms.

Hackish? way, $watch the ng-model in your controller:

<input type="text"  ng-model="myText" name="inputName">

Controller:

$scope.$watch('myText', function() {
// put numbersOnly() logic here, e.g.:
if ($scope.myText ... regex to look for ... ) {
// strip out the non-numbers
}
})

Best way, use a $parser in a directive.
I'm not going to repeat the already good answer provided by @pkozlowski.opensource, so here's the link: https://stackoverflow.com/a/14425022/215945

All of the above solutions involve using ng-model, which make finding this unnecessary.

Using ng-change will cause problems. See AngularJS - reset of $scope.value doesn't change value in template (random behavior)

How to accept only numeric numbers which has maximum 5 length for an input in Angular?

The maxLength is ignored on <input type="number">
Read:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input#attr-

You can use the max Validator to enforce a max length of 5

Hence your .ts will look like this.

 public searchForm: FormGroup = new FormGroup({
zip: new FormControl("",[Validators.required,Validators.pattern(/^-?(0|[1-9]\d*)?$/), Validators.max(99999)]),
});

Update

Another way to tackle this problem is IF type=number is not mandatory in your use case, is to remove type=number. Then the Regex that you are already using will do the validation for you and it will disable the button if the user does not input a number



Related Topics



Leave a reply



Submit