Reputation: 544
I have a form in Angular which i want that the user will only submit a full number (not decimal) and he will not have the option to write .(dot) symbol in the form in order to write the decimal number. I want to block completely the option to write .(dot) at the form. Is it possible?
I tried the solution here : Proper way to restrict text input values (e.g. only numbers) Using regex :
In component.ts add this function
_keyUp(event: any) {
const pattern = /[0-9\+\-\ ]/;
let inputChar = String.fromCharCode(event.charCode);
if (!pattern.test(inputChar)) {
// invalid character, prevent input
event.preventDefault();
}
}
In your template use the following
<input(keyup)="_keyUp($event)">
But it did not work, the option to write .(dot) at the form is still possible.
I want to block completely the option to write .(dot) at the form.
Upvotes: 0
Views: 653
Reputation: 5131
@CDelaney is correct, but some additional thoughts: This (found) stackblitz I would say does it better:
Component html:
<input (keypress)="numberOnly($event)" type="text">
and the TS file:
numberOnly(event): boolean {
const charCode = (event.which) ? event.which : event.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
Why it's better?
No regex: as the saying goes, if you try to solve a problem with Regex, now you have two problems.
Keypress, it will be closer to what you want without having to replace strings
Better event names. If I had my druthers _namesOfAnything would never be a thing.
Upvotes: 1
Reputation: 1248
I believe the character is already present at the time of the keyup
event, and you can't prevent something that has already happened. Try the keypress
event:
<input (keypress)="_keyUp($event)">
Upvotes: 2