问题描述
ngOnInit(): void {
this.customerForm = this.fb.group({
name: ['',Validators.required],customer_id: ['',})
}
我有这个表格组。因此,这是一个包含名称和customer_id的表单。我需要验证名称字段,它不应该接受任何特殊字符。如果可能的话,在使用烤面包机时也要提及
<td>
<mat-form-field>
<mat-label>Name</mat-label>
<input matInput placeholder="Name" formControlName="name" autocomplete="off" required>
</mat-form-field>
</td>
解决方法
希望这对您有所帮助:
// Array of all special characters
var specialChars = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;
// Loop through array
for (let i = 0; i < specialChars.length; i++) {
// Checks if input contains current character
if (this.name.includes(specialChars[i])) {
// Your output
console.log("User input contained a special character");
break;
}
}
,
您可以创建一个自定义验证器,以将其添加到表单“名称”中,以便每次检查失败时,表单都会返回无效状态,因此您可以在某处显示一条消息
datastore.delete(taskKey);
现在将CustomValidators添加到组件构造函数中:
export class CustomValidators {
nameValidator(control: FormControl): { [key: string]: boolean } {
const nameRegexp: RegExp = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;
if (control.value && nameRegexp.test(control.value)) {
return { invalidName: true };
}
}
}
然后可以在mat-form-field下方的模板上向用户显示mat-error
...
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],});
}
}
您可以使用Validators(内置的Validators)执行类似的操作。
有关表单验证的更多信息,请检查this