简体   繁体   中英

How to restrict reserved characters in input field using angular8

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();
    }
  }

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"
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM