特殊字符不应以反应形式的第一个字符出现-Angular 7

时间:2019-04-11 08:04:28

标签: angular typescript

在这里,我有一个小情况,即用户不应该输入特殊字符作为起始字符。此后应该允许他们。

component.ts

this.new_org = this.fb.group({
    firstName: [this.data.name, [Validators.required, Validators.minLength(8),Validators.pattern('^[a-zA-Z \-\']+')]],
});

component.html

<mat-form-field appearance="outline" fxFlex="100%">
  <mat-label>Name</mat-label>
  <input class="add-org" matInput placeholder="" formControlName="firstName" type="text" required>
</mat-form-field>
<mat-error
  *ngIf="new_org.get('firstName').hasError('minlength') || new_org.get('firstName').hasError('pattern')">
  <span style="color:red;font-family:Open-Sans">Name must be 8 characters Long!.Special characters(@,#,!) and Numbers
    are not allowed.</span>
</mat-error>

如何在第一个输入的字符中限制特殊字符?

3 个答案:

答案 0 :(得分:0)

Validators.pattern('^[a-zA-Z \-\']')应该在正则表达式中没有加号。

答案 1 :(得分:0)

您可以创建一个自定义验证器

import { FormControl } from '@angular/forms';

export function ValidateString(control: FormControl) {
    let pattern = /[*\\/|":?><]/gi; // can change regex with your requirement
    //if validation fails, return error name & value of true
    if (pattern.test(control.value)) {
        return { validString: true };
    }
    //otherwise, if the validation passes, we simply return null
    return null;
}

并更新您的表单

organisationName: [this.data.name, [Validators.required, Validators.minLength(8),ValidateString]],

答案 2 :(得分:0)

您已经有一个模式验证器,因此您只需将正则表达式更新为适合您要求的内容即可。当前的正则表达式(^[a-zA-Z \-\']+)允许所有常规字母和以下字符\-'

您可以使用如下正则表达式:^\w.*来确保第一个字符是常规字符(a-zA-Z),其他所有字符都可以是任何字符。

更新:

正则表达式,不允许在第一个字符后添加数字,但其他任何条件: ^[a-zA-Z][^0-9]*$

您可以根据需要使正则表达式既大又复杂。