动态更改角度2 Validators.maxLength的maxLength值

时间:2016-11-14 12:03:20

标签: javascript validation angular

在表单组验证中,我尝试应用输入最大长度,但是,此最大长度取决于表单中的其他操作。如果它们发生变化,也会改变maxMsgLength的属性值。

msg:['',Validators.maxLength(this.maxMsgLength)],

然而,在更改maxMsgLength之后,验证器会坚持使用旧的maxMsgLength值。是否有方法使用maxLength的新值?

重新启动此验证字段的验证

代码:     班级帐号{     maxMsgLength = 200;     newAccount:FormGroup;

//activated by click on another method
    private changeMaxMsgLength() : void {
    let values = Object.values(this.accountsStorage);
    if(values.includes("oldAccount")) {
      this.maxMsgLength = 150;
    } else {
      this.maxMsgLength = 200;
    }
  }

  ngOnInit(): void {
    this.newAccount = this.formbuilder.group({
      msg         : ['', Validators.maxLength(this.maxMsglength)],
      link        : ['', Validators.pattern('^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$')],
      schedule    : ['', Validators.pattern('^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]) (2[0-3]|[01][0-9]):[0-5][0-9]$')]
    });

  }

} 
 //where in template there is 


<div class="form-group">
    <label for="name">Message</label>
    <textarea class="form-control" id="Message" formControlName="msg" style="width: 300px; height: 150px;"></textarea>
</div>
<div class="error" *ngIf="newAccount.get('msg').hasError('maxlength')">
    Maximum of {{maxMsglength}} characters
</div>

1 个答案:

答案 0 :(得分:0)

您可以使用html输入的merge.renormalize属性:

maxlength