1

My type script code to restrict only alphabets:

InputValidatorChar(event:any){

    Const pattern= /^[a-zA-Z]*$/;
    If(!      pattern.test(event.target.value)){
event.target.value=event.target.value.replace(/[^a-zA-Z/g,"");
}}

Expected output: Should accept only alphabets (example: jekrhrjek)

Output I am getting: Accepting only characters. But if I type any integer at end of the sentence as input and click outside of cell then the last typed integer is getting populated.

How to overcome this problem?

2
  • Can you show a simple Stackblitz example, or some code? Commented Nov 20, 2022 at 10:55
  • You also have a typo in here: ...[^a-zA-Z/g... after the A-Z missing closing ]. Commented Nov 20, 2022 at 21:37

1 Answer 1

1

Instead of first testing if there are only chars A-Z a-z or an empty string, you might opt for running only the replacement.

Note that you have to close the character class [^a-zA-Z]+ and you can match 1 or more times to replace it with an empty string.

InputValidatorChar(event:any){
  event.target.value=event.target.value.replace(/[^a-zA-Z]+/g, "");
}
Sign up to request clarification or add additional context in comments.

3 Comments

I don't think we need the + there, the regExp itself means replace all non-character
@Jimmy Yes but the total number of replacements will be less if you use a quantifier to gather all matches in sequence at once.
this goes "too far" for me ^_^ there's a lot behind a Regular expression, the expression itself and the engine that executes it, we even have ReDoS, so I won't go into detail here :D

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.