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();
    }
  }
Bhrungarajni
  • 2,415
  • 11
  • 44
  • 88

1 Answers1

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"
/>
Mohrn
  • 816
  • 4
  • 15
  • 1
    https://stackoverflow.com/questions/54460923/angular-2-restrict-input-field/54462816#54462816 – Eliseo Sep 01 '20 at 16:01
  • @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 Sep 02 '20 at 07:51
  • @Bhrungarajni, there are a problem with the doble quotes, so, declare a variable in your .ts `mask='^((?![<>\/?|\\*:"]).)+$'` and use `[mask]="mask"` – Eliseo Sep 02 '20 at 10:55