How can I block the user input entering commas in case of negative decimals with regex in typescript angular 2?

huangapple go评论83阅读模式
英文:

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 &quot;pattern&quot;.

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>



huangapple
  • 本文由 发表于 2023年1月6日 11:06:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75026557.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定