验证角度中的特殊字符

问题描述 投票:0回答:3
ngOnInit(): void {
  this.customerForm = this.fb.group({
    name: ['', Validators.required],
    customer_id: ['', Validators.required],        
  })
}

我有这个有角度的表格组。这是一个包含名称和 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>
angular forms angular6 angular8
3个回答
5
投票

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

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 执行类似的操作。

有关表单验证检查的更多信息这个


0
投票

公共 getResults(值: 字符串): void { const counts = { 数字:0,字符:0,特价:0 };

for (const char of value) {
  if (/\d/.test(char)) {
    counts.numbers++;
  } else if (/[a-zA-Z]/.test(char)) {
    counts.characters++;
  } else if (/[^a-zA-Z\d\s]/.test(char)) {
    counts.specials++;
  }
}

this.numCount = counts.numbers;
this.charCount = counts.characters;
this.specialCount = counts.specials;

}


-1
投票

希望这对您有帮助:

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