如何在PrimeNg表编辑器中进行正则表达式验证?

问题描述 投票:-1回答:1

我正在使用PrimeNG DataTable编辑器。我想为每个字段使用Regex实现验证。

正则表达式验证:仅限数字且仅限字母表。

如何才能做到这一点?

angular primeng-datatable
1个回答
0
投票

您可以使用(keyup)或(onBlur)事件来实现它。

在您的component.html文件中

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

在component.ts文件中

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');
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.