首页 > 解决方案 > 验证角度中的特殊字符

问题描述

ngOnInit(): void {
  this.customerForm = this.fb.group({
    name: ['', Validators.required],
    customer_id: ['', Validators.required],        
  })
}

我有这个有角度的表单组。所以这是一个包含名称和客户 ID 的表单。我需要的是我想验证名称字段。它不应该接受任何特殊字符。如果可能的话,请在使用 toastr 时提及

<td>
    <mat-form-field>
        <mat-label>Name</mat-label>
        <input matInput placeholder="Name" formControlName="name" autocomplete="off" required>
    </mat-form-field>
</td>

标签: angularformsangular6angular8

解决方案


您可以创建一个自定义验证器以添加到您的表单“名称”,以便每次检查失败时表单将返回无效状态,以便您可以在某处显示消息

export class CustomValidators {
    nameValidator(control: FormControl): { [key: string]: boolean } {
        const nameRegexp: RegExp = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;
        if (control.value && nameRegexp.test(control.value)) {
           return { invalidName: true };
        }
    }
}

现在将 CustomValidators 添加到组件构造函数中:

...
export class YourComponent implements OnInit {
    constructor(private customValidators: CustomValidators) {
        this.customerForm = this.fb.group({
            name: ['', Validators.compose([Validators.required, this.customValidators.nameValidator])],
            customer_id: ['', Validators.required],
        });
    }
}

然后可以在 mat-form-field 下方的模板上向用户显示 mat-error

<td>
    <mat-form-field>
        <mat-label>Name</mat-label>
        <input matInput placeholder="Name" formControlName="name" autocomplete="off" required>
    </mat-form-field>
    <mat-error *ngIf="form.controls['name'].hasError('invalidName')">
        Special characters not allowed!
    </mat-error>
</td>

您可以使用内置的 Validators.required 执行类似的操作。

有关表单验证的更多信息,请查看


推荐阅读