Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
187
rated 0 times [  189] [ 2]  / answers: 1 / hits: 23414  / 8 Years ago, wed, december 21, 2016, 12:00:00

I have to restrict user to enter only numbers in a field in Angular2->form
I have solution but backspace is not working in input field
Can anybody have proper solution for that?



form.html



<input (keypress)=keyPress($event) minlength=8 maxlength=15 required />



form.component.ts



keyPress(event: any) {
const pattern = /[0-9+- ]/;
let inputChar = String.fromCharCode(event.charCode);
// console.log(inputChar, e.charCode);
if (!pattern.test(inputChar)) {
// invalid character, prevent input
event.preventDefault();
}
}


On kepress event it restrict user to enter only numbers but problem with this code is backspace, tab keys are not working.So, this code is not as per my expectation...


More From » angular

 Answers
7

my answer is :-
form.html:





form.component.ts



restrictNumeric = function (e) {
var input;
if (e.metaKey || e.ctrlKey) {
return true;
}
if (e.which === 32) {
return false;
}
if (e.which === 0) {
return true;
}
if (e.which < 33) {
return true;
}
input = String.fromCharCode(e.which);
return !!/[ds]/.test(input);
}

[#59618] Monday, December 19, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
havenbilliec

Total Points: 324
Total Questions: 106
Total Answers: 94

Location: Pitcairn Islands
Member since Fri, Oct 15, 2021
3 Years ago
;