-1

I am using PrimeNG DataTable editor. I want to implement validation with Regex for each field.

Regex Validation: only number and only alphabets.

How can this be done?

Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42
Kamaraj G
  • 11
  • 1
  • 6

1 Answers1

0

You can achieve it using (keyup) or (onBlur) event.

In your component.html file

<p-table [value]="cars">
    <ng-template pTemplate="header">
        <tr>
            <th>Name</th>
            <th>Motor</th>
        </tr>
    </ng-template>
    <ng-template pTemplate="body" let-rowData>
        <tr>
            <td pEditableColumn>
                <p-cellEditor>
                    <ng-template pTemplate="input">
                        <input pInputText type="text" [(ngModel)]="rowData.name" (keyup)="onKey(rowData.name)">
                    </ng-template>
                    <ng-template pTemplate="output">
                        {{rowData.name}}
                    </ng-template>
                </p-cellEditor>
            </td>
            <td pEditableColumn>
                <p-cellEditor>
                    <ng-template pTemplate="input">
                        <input pInputText type="text" [(ngModel)]="rowData.motor" required>
                    </ng-template>
                    <ng-template pTemplate="output">
                        {{rowData.motor}}
                    </ng-template>
                </p-cellEditor>
            </td>
        </tr>
    </ng-template>
</p-table>

In component.ts file

public cars: any[];
public letters = /^[0-9a-zA-Z]+$/;
  constructor(){
    this.cars = [];
    this.cars.push({name: 'Audi', motor: '100ch'});
    this.cars.push({name: 'Honda', motor: '200ch'});
    this.cars.push({name: 'Mercedes', motor: '100ch'});
    this.cars.push({name: 'Renault', motor: '100ch'});
    this.cars.push({name: 'VW', motor: '100ch'});
  }
onKey(event:any){
    if(!event.match(this.letters))
    {
     console.log('Please input alphanumeric characters only');
    }
  }
DirtyMind
  • 2,353
  • 2
  • 22
  • 43