【问题标题】:Angular conditional validations角度条件验证
【发布时间】:2020-01-27 20:50:48
【问题描述】:

我在我的角度形式中使用 mat 表单字段,我的属性之一的代码如下。

<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


【解决方案1】:

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

类似这样的:

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

【讨论】:

  • 我需要在哪里添加此代码。在我定义了表单组并添加 vlaidations 的组件或服务类中?
  • 我如何获得所需的消息?
  • 检查修改后的答案,如果它无效,你可以用 *ngIf 将它保存在一个块中来显示一条消息
  • 我理解你的代码。但是没有得到如何使用 *ngIf 有条件地显示所需的消息。你能举个例子吗?
【解决方案2】:

基于国家选择更新验证器 假设您选择国家为“印度”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) 替换为您所在国家/地区的字符长度。

【讨论】:

  • 我需要将它添加到我的组件中吗?我是否需要更改包含表单组和验证器的 html 代码或服务代码中的任何内容?
猜你喜欢
  • 2020-10-26
  • 2019-03-22
  • 2020-09-23
  • 1970-01-01
  • 2013-09-17
  • 1970-01-01
  • 2015-02-25
  • 2018-03-09
  • 2020-10-27
相关资源
最近更新 更多