Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

javascript - 使用正则表达式删除数字以外的字符并仅允许在Typescript中使用一个小数点(Regular expression to remove characters other than number and allow single decimal dot only in Typescript)

I have read similar questions and no solutions seem to be working for this.(我读过类似的问题,似乎没有解决方案。)

I have a Angular material input box.(我有一个角度材料输入框。) The input should receive only numbers and a decimal dot.(输入应仅接收数字和小数点。) All other characters should be identified and removed on keypress removal.(所有其他字符都应在删除按键时识别并删除。) This is my code:(这是我的代码:) In TS file and html:(在TS文件和html中:) allownumbersonly(inputVal) { inputVal = inputVal.replace(/[^0-9.]/g, '');//Modified after responses from stack overflow. this.myForm.controls['inNum'].setValue(inputVal); } <mat-form-field> <input id="inputNumber" matInput (keyup)="allownumbersonly($event.target.value)" placeholder="enter a number" formControlName="inNum"> </mat-form-field> Please help.(请帮忙。) Thanks in advance.(提前致谢。)   ask by AngularDoubts translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use keypress event:(您可以使用keypress事件:)

<input (keypress)="isNumberKey($event)"/> and typescript:(和打字稿:) isNumberKey(evt){ console.log(evt.keyCode); let charCode = (evt.which) ? evt.which : evt.keyCode; if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; } Work example can be seen here(工作示例可以在这里看到)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...