0

I'm not sure what this is called. It's really simple. I tried using a pipe, but I got an error. I'm looking for something as simple as:

<input [(ngModel)]="order.name | lettersOnlyPipe"/>

That doesn't work. What can I do that would accomplish this?

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
BBaysinger
  • 6,614
  • 13
  • 63
  • 132
  • Do you want to prevent them from being entered? Or filter them out after they are entered? If the later, then a pipe will work. If the former, then a pattern or directive may be your best option. – DeborahK Apr 01 '17 at 03:23
  • Take a look on [text-mask](https://github.com/text-mask/text-mask). – developer033 Apr 07 '17 at 18:58

5 Answers5

2

With the recent Angular 4 release, you can use the pattern attribute to restrict characters as mentioned in this feature

<input [(ngModel)]="order.name" pattern="" />

In other case, you should handle it using custom directive. Refer to this answer for a sample.

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Aravind
  • 40,391
  • 16
  • 91
  • 110
  • 4
    I tried using the pattern attribute like you pointed out. It made the field show an error, but didn't prevent the user from entering characters. – BBaysinger Apr 03 '17 at 18:15
1

Your best bet for this is your own directive.

Some simple ideas to get you going:

  • your directive monitors the input event on its host element
  • on every input event, you check whether the input value is valid, if not, you set your input back to its old value

or alternatively, * monitor the keydown event and on each keydown, check if the key is a valid key - if not, set your input back to its old value

That's the basic approach. You can look at the highlight directive example in the angular docs as a guide to get going.

snorkpete
  • 14,278
  • 3
  • 40
  • 57
1

I posted a similar response here, you'll just need to change regex (remove numbers and perhaps arabic characters from it). Hope it helps.

sivi911
  • 311
  • 3
  • 5
1
input [name]="fullName" pattern="[a-zA-Z ]*" ngModel 

In angular 4 you can use Pattern attribute and specify pattern as = [a-zA-Z ] for only letters.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
1

Using the pattern attribute do not prevent entering anything inside the input field. It will just mark it as invalid. You must use a Directive to do so. Here is a simple example that prevent entering anything but positive number into a input field:

import {Directive, HostListener} from '@angular/core';

@Directive({
  selector: 'input[dsancNumeroPositif]'
})
export class NumeroPositifDirective {

  acceptedCharacters: string[] = ['.', ',', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

  constructor() { }

  @HostListener('keypress', ['$event']) onInput(event: KeyboardEvent): void
  {
    if (!this.acceptedCharacters.includes(event.key)) {
      event.preventDefault();
    }
  }

}
tleveque
  • 507
  • 3
  • 9
  • 16