【问题标题】:Add dynamic FormControl Validators without removing old ones添加动态 FormControl 验证器而不删除旧的
【发布时间】:2018-11-05 14:50:42
【问题描述】:

我有如下表格

this.personForm = new FormGroup({
            title: new FormControl(this.person.salutation, Validators.compose([
            Validators.minLength(2)
        ])),
            firstName: new FormControl(this.person.firstName, Validators.compose([
            Validators.minLength(4)
        ])),
});

基于来自 API 调用的配置,我想让它们动态地被需要或不需要。我知道我可以使用formControl.setValidators([Validators.required]),但这会清除现有的验证器。

我希望通过以下方式之一实现它

  • 仅用于添加的函数(Exp:addValidators([])
  • OR 一个函数,它将为我提供 formControl 已经拥有的验证器列表,以便我可以将它们与我想要添加的内容一起加入。 (Exp: getValidators())

不幸的是(据我所知)以上 2 个功能都不存在。那么如何在不知道已经存在的情况下向 formControl 添加新的 Validation 呢?

【问题讨论】:

  • 你能分享你的服务器验证json吗
  • @AjayOjha 这都是前端,服务器验证是什么意思? API 只会给我一个布尔数组,让我知道是否需要 formControls。剩下的都是前端
  • 我以为动态规则是来自服务器,现在明白了,根据你要应用的条件需要?
  • @AjayOjha 那部分只是业务逻辑,不要混淆。为简单起见,请考虑一下:如何在表单初始化但不丢失旧验证(在本例中为 Validator.minLength(2))后向title 添加额外的验证?谢谢
  • 请参阅此提供的链接以进行有条件要求的验证rxweb.io/validation-validators/required#conditionalexpression,如果这不能满足您的需求,请告诉我。

标签: angular forms validation angular-validation


【解决方案1】:

我想你可以使用一个依赖于一个变量的 customValidator,在这个例子中,一个按钮使一个变量“仍然”为真或假。取决于表格是否有效

@Component({
  selector: 'my-app',
  template:`
  <form [formGroup]="personForm">
     <input formControlName="title"/>
     <input formControlName="firstName"/>
  </form>
  <button (click)="addValidator()">click</button>
  <hr/>
  {{personForm?.errors|json}}
  {{personForm?.valid}}`
})
export class AppComponent implements OnInit {
  yet: boolean;
  personForm: FormGroup;
  person = { salutation: "", firstName: "" }
  ngOnInit() {
    this.personForm = new FormGroup({
      title: new FormControl(this.person.salutation, Validators.compose([
        Validators.maxLength(2)
      ])),
      firstName: new FormControl(this.person.firstName, Validators.compose([
        Validators.minLength(4)
      ])),
    }, this.customValidator())
  }
  addValidator() {
    this.yet = !this.yet;
    this.personForm.updateValueAndValidity();
  }
  customValidator() {
    return (group: FormGroup) => {
      if (!this.yet)
        return null;
      if (group.get('title').value == '')
        return { title: 'required' }
    }
  }

stackblitz

【讨论】:

  • 有趣的想法,将尝试一下。谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-08-11
  • 2016-08-01
  • 2020-12-23
  • 1970-01-01
  • 2019-11-24
  • 2016-11-08
  • 2017-05-01
  • 1970-01-01
相关资源
最近更新 更多