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

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

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!!!!

  1. private el: HTMLInputElement;
  2. private check(value: string) {
  3. const regExpString = "^-?\\s*((\\d+(\\.\\d{0,5})?)|((\\d*(\\.\\d{1,5}))))\\s*$";
  4. return String(value).match(new RegExp(regExpString));
  5. }
  1. @HostListener("keydown", ["$event"])
  2. onKeyDown(v) {
  3. const value: string = this.el.value;
  4. const next: string = value.concat(v.key);
  5. console.log(this.check(next))
  6. if (next && !this.check(next)) {
  7. v.preventDefault();
  8. }
  9. }
英文:

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!!!!

  1. private el: HTMLInputElement;
  2. private check(value: string) {
  3. const regExpString = "^-?\\s*((\\d+(\\.\\d{0,5})?)|((\\d*(\\.\\d{1,5}))))\\s*$";
  4. return String(value).match(new RegExp(regExpString));
  5. }
  1. @HostListener("keydown", ["$event"])
  2. onKeyDown(v) {
  3. const value: string = this.el.value;
  4. const next: string = value.concat(v.key);
  5. console.log(this.check(next))
  6. if (next && !this.check(next)) {
  7. v.preventDefault();
  8. }
  9. }```
  10. </details>
  11. # 答案1
  12. **得分**: 1
  13. 通过HTML文件 - 使用“pattern”在HTML文件中应用数字或字母的验证。
  14. 通过TS文件 - 使用逗号验证的ASCII值。如果用户输入逗号,则将匹配逗号的ASCII代码。使用if else。
  15. <details>
  16. <summary>英文:</summary>
  17. Through HTML file - Apply validations for numbers or alphabets in html file using &quot;pattern&quot;.
  18. Through TS file - Use ASCII values for comma validations. If user enters a comma, ASCII code for comma will be matched. Use if else .
  19. </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:

确定