DEV Community

loading...
Cover image for Angular KeyFilter

Angular KeyFilter

primetek profile image PrimeTek ・1 min read

Angular KeyFilter directive restricts user input based on a regular expression.

Setup

Refer to PrimeNG setup documentation for download and installation steps for your environment.

Import

import {KeyFilterModule} from 'primeng/keyfilter';
Enter fullscreen mode Exit fullscreen mode

 Getting Started

KeyFilter directive is applied to an input text element using pKeyFilter attribute whose value is either a built-in regular expression name or a custom one. Following input only accepts integers.

<input type="text" pKeyFilter="int">
Enter fullscreen mode Exit fullscreen mode

Built-in Filters

Commonly used cases have their own built-in shortcuts.

  • pint: Positive integers
  • int: Integers
  • pnum: Positive numbers
  • num: Numbers
  • hex: Hexadecimal
  • email: Email
  • alpha: Alphabetic
  • alphanum: Alphanumeric

Custom Filter

A custom filter is provided by binding a regular expression, here is an example that blocks special characters including "< > * !"

<input type="text" [pKeyFilter]="noSpecial">
Enter fullscreen mode Exit fullscreen mode
export class KeyFilterDemo {

     noSpecial: RegExp = /^[^<>*!]+$/

}
Enter fullscreen mode Exit fullscreen mode

Validate Mode

Instead of blocking a single keypress, the alternative validation mode which is enabled with pValidateOnly property validates the whole input with a built-in Angular validator.

<form #form="ngForm"> 
    <label for="cc">Credit Card</label> 
    <input id="cc" type="text" name="cc" [(ngModel)]="cc" pInputText [pKeyFilter]="ccRegex" [pValidateOnly]="true" placeholder="1234-1234-1234-1234">
    <p-message severity="error" text="Not a valid number" [@errorState]="form.dirty && !form.valid ? 'visible' : 'hidden'"></p-message>
</form>
Enter fullscreen mode Exit fullscreen mode

Theming

KeyFilter supports various themes featuring Material, Bootstrap, Fluent as well as your own custom themes via the Designer tool.

Resources

Visit the PrimeNG KeyFilter showcase for demos and documentation.

Discussion (0)

Forem Open with the Forem app