Angular条件验证

问题描述 投票:0回答:2

我正在以角形形式使用垫子形式字段,而我的属性之一的代码如下。

<mat-form-field appearance="fill">
  <mat-label>CountryCode</mat-label>
  <input formControlName="CountryCode" matInput (click)='updateFormTextValue("alphanumericNext", "CountryCode")'>
  </mat-error>
</mat-form-field>

我想为此字段添加验证,以便如果国家是加拿大,则要执行Validators.required和Validators.maxLength(30),如果国家不是加拿大,则只需检查最大长度。我该怎么办?

我在服务类中的代码如下

CountryCode: new FormControl('', [Validators.required, Validators.maxLength(30)]),

我能够使用angular提供的验证器作为我上面的代码,但是不知道如何根据条件进行验证。我在StackOverflow上看到了一些示例,但没有得到如何做。

PS:我需要检查的国家/地区是表单中的字段之一,其代码与上述的CountryCode相同。请帮助

此外,还需要显示消息,如果最大长度超过则显示消息“应显示最大长度超过”,如果该字段为空,并且国家/地区为加拿大,则显示消息“必填字段”]

angular angular6 angular7 angular8
2个回答
0
投票

基于国家选择更新验证器假设您选择国家作为“印度” selectedCountry="India"

  if(selectedCountry===India'){
    this.myForm.controls.get('CountryCode').setValidators([Validators.required, 
                                              Validators.maxLength(5)]);
}else{
 this.myForm.controls.get('CountryCode').setValidators([Validators.required, 
                                              Validators.maxLength(4)]);
}

您可以使用国家/地区字符长度替换maxLength(4)


0
投票

您必须创建一个自定义验证器

类似这样的东西:

CountryCode: new FormControl('', [CountryCodeValidator('Canada')]),

function CountryCodeValidator(countryName: string): ValidatorFn {
  return (control: AbstractControl): { [key: string]: boolean } | null => {
    if (countryName == "Canada") {
      if (control.value.length >= 30) {
        return null
      } else {
        return { 'CountryCode': true };
      }
    } else {
      return null
    }
  };
}

阅读有关此here的更多信息

© www.soinside.com 2019 - 2024. All rights reserved.