0

Hi i am using angular8 in my application, i have a file name input field, which should contain alphanumeric characters and except reserved characters other special characters to be allowed. Is there any way to have a directive for that or inline code, and it must restrict pasting of these reserved characters.

The following reserved characters shouldnt be allowed:

< (less than) > (greater than) : (colon) " (double quote) / (forward slash) \ (backslash) | (vertical bar or pipe) ? (question mark) * (asterisk) 

HTML:

<input type="text" class="form-control" placeholder="Custom File Name" name="fileName" autocomplete="off" (keypress)="keyPress($event)"> 

Ts:

 public keyPress(event: any) { const pattern = /[0-9\-\ ]/; let inputChar = String.fromCharCode(event.charCode); if (!pattern.test(inputChar) && event.charCode != '0') { event.preventDefault(); } } 

1 Answer 1

0

Use a reactive form and clean the input on changes. Works for both copy paste and typing.

 public restricted = new FormControl(); ngOnInit() { this.restricted.valueChanges.subscribe((val) => { const restrictedCharacters = /[-+]/g // Add more restricted characters here if (restrictedCharacters.test(val)) { this.restricted.setValue(val.replace(restrictedCharacters, '')) } }); } 

In your template add the restricted form control to your input.

<input [formControl]="restricted" type="text" placeholder="Custom File Name" name="fileName" /> 
Sign up to request clarification or add additional context in comments.

3 Comments

@Eliseo i have tried as you have answered and have modified few things, but i am not able to type anything in my input field, when debugged it is going as empty string.
@Bhrungarajni, there are a problem with the doble quotes, so, declare a variable in your .ts mask='^((?![<>\/?|\\*:"]).)+$' and use [mask]="mask"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.