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?

2
  • 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. Commented Apr 1, 2017 at 3:23
  • Take a look on text-mask. Commented Apr 7, 2017 at 18:58

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

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.

Comments

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.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.