【问题标题】:Validators.pattern is not showing the error for mobile numberValidators.pattern 未显示手机号码错误
【发布时间】:2020-06-24 04:06:55
【问题描述】:

component.html

<div class="form-group">
            <label>Enter mobile</label>
            <input type="text" class="form-control" formControlName="mobile" ><br>
        </div>
        <div *ngIf="userGroup.controls.mobile.invalid && (userGroup.controls.mobile.dirty || userGroup.controls.mobile.touched)">
            <div *ngIf="userGroup.controls.mobile.errors.required">
                Mobile number cannot be blank
            </div>
            <div *ngIf="userGroup.controls.mobile.errors.pattern">
                Mobile number should be 10 digits only
            </div>
        </div>

组件.ts

userGroup:FormGroup;

ngOnInit() { this.userGroup = this.fb.group({

 mobile:['',Validators.required,Validators.pattern(/^[0-9]{10}$/)]
});

}

对于空白,它工作得很好,但对于模式,它没有显示任何错误

【问题讨论】:

  • 我认为您的控制台会抛出以下错误:预期的验证器会返回承诺或可观察到的角度。所以请使用以下链接解决问题。 stackoverflow.com/questions/50548062/…
  • 我认为@Jinu 的回答可以解决您的问题。有关更多信息,请查看我提供的链接。

标签: javascript node.js angular angular-reactive-forms


【解决方案1】:

试试这样:

mobile:['',[Validators.required,Validators.pattern(/^[0-9]{10}$/)]]
});

【讨论】:

    【解决方案2】:

    组件.ts

    userGroup:FormGroup;
    
    //simple getter to easily access control from template
    get mobile() { return this.userGroup.get('mobile'); }
    
    ngOnInit() { 
       this.userGroup = this.fb.group({
          //also validators should passed in one array as a second argument to this literal
          mobile:['', [Validators.required, Validators.pattern(/^[0-9]{10}$/)]]
    });
    

    component.html

    <div class="form-group">
       <label>Enter mobile</label>
       <input type="text" class="form-control" formControlName="mobile"><br>
    </div>
    <div *ngIf="mobile.invalid && (mobile.dirty || mobile.touched)">
       <div *ngIf="mobile.errors.required">
          Mobile number cannot be blank
       </div>
       <div *ngIf="mobile.errors.pattern">
          Mobile number should be 10 digits only
       </div>
    </div>
    

    【讨论】:

      【解决方案3】:

      对于超过 1 个验证器,您应该在数组中使用它作为第二个参数。否则它将在控制台上返回错误并且不会工作。

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 1970-01-01
      • 2020-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-09
      相关资源
      最近更新 更多