英文:
How can I block the user input entering commas in case of negative decimals with regex in typescript angular 2?
问题
I have a component directive shared for all fields, but I want to add a rule for a field specific, this field block user input commas, I have the following code in file ts but it only satisfies the condition for positive decimals (ex: 2323.34343) else case negative decimals (ex: -3232.323) I can't enter a minus sign because of the regex check function not match with the first character being the minus sign. How can I fix it? pls help me, thanks a lot!!!!
private el: HTMLInputElement;
private check(value: string) {
const regExpString = "^-?\\s*((\\d+(\\.\\d{0,5})?)|((\\d*(\\.\\d{1,5}))))\\s*$";
return String(value).match(new RegExp(regExpString));
}
@HostListener("keydown", ["$event"])
onKeyDown(v) {
const value: string = this.el.value;
const next: string = value.concat(v.key);
console.log(this.check(next))
if (next && !this.check(next)) {
v.preventDefault();
}
}
英文:
I have a component directive shared for all fields, but I want to add a rule for a field specific, this field block user input commas, I have the following code in file ts but it only satisfies the condition for positive decimals (ex: 2323.34343) else case negative decimals (ex: -3232.323) I can't enter a minus sign because of the regex check function not match with the first character being the minus sign.
How can I fix it? pls help me, thanks a lot!!!!
private el: HTMLInputElement;
private check(value: string) {
const regExpString = "^-?\\s*((\\d+(\\.\\d{0,5})?)|((\\d*(\\.\\d{1,5}))))\\s*$";
return String(value).match(new RegExp(regExpString));
}
@HostListener("keydown", ["$event"])
onKeyDown(v) {
const value: string = this.el.value;
const next: string = value.concat(v.key);
console.log(this.check(next))
if (next && !this.check(next)) {
v.preventDefault();
}
}```
</details>
# 答案1
**得分**: 1
通过HTML文件 - 使用“pattern”在HTML文件中应用数字或字母的验证。
通过TS文件 - 使用逗号验证的ASCII值。如果用户输入逗号,则将匹配逗号的ASCII代码。使用if else。
<details>
<summary>英文:</summary>
Through HTML file - Apply validations for numbers or alphabets in html file using "pattern".
Through TS file - Use ASCII values for comma validations. If user enters a comma, ASCII code for comma will be matched. Use if else .
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论