Angular KeyFilter

Angular KeyFilter

·

2 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';

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

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">
export class KeyFilterDemo {

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

}

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>

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.