Exp*_*abs 1 forms angular angular6 angular8
ngOnInit(): void {
this.customerForm = this.fb.group({
name: ['', Validators.required],
customer_id: ['', Validators.required],
})
}
Run Code Online (Sandbox Code Playgroud)
我有这个有角度的表格组。这是一个包含名称和 customer_id 的表单。我需要的是我想验证名称字段。它不应该接受任何特殊字符。如果可能的话,请在使用 toastr 时提及
<td>
<mat-form-field>
<mat-label>Name</mat-label>
<input matInput placeholder="Name" formControlName="name" autocomplete="off" required>
</mat-form-field>
</td>
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以创建一个自定义验证器来添加到您的表单“名称”中,这样每次检查失败时,表单都会返回无效状态,以便您可以在某处显示消息
export class CustomValidators {
nameValidator(control: FormControl): { [key: string]: boolean } {
const nameRegexp: RegExp = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;
if (control.value && nameRegexp.test(control.value)) {
return { invalidName: true };
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在将 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],
});
}
}
Run Code Online (Sandbox Code Playgroud)
然后可以在 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>
Run Code Online (Sandbox Code Playgroud)
您可以使用内置的 Validators.required 执行类似的操作。
有关表单验证的更多信息,请检查此
| 归档时间: |
|
| 查看次数: |
23259 次 |
| 最近记录: |