2

In form group validation I try to apply input maximum length, however, this max length depends of other action in form. If they change, also change value of property of maxMsgLength.

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

However after change of maxMsgLength, validator stick to old maxMsgLength value. Is there a method to restart validation for this validation field with new value of maxLength?

Code: class Account { 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
  • Also doesn' work this.newAccount.controls['msg'].updateValueAndValidity(); Commented Nov 14, 2016 at 20:43

2 Answers 2

3

You can use maxlength attribute of your html input for it :

<input [attr.maxlength]="maxMsgLength" />
Sign up to request clarification or add additional context in comments.

Comments

1

Found out the answer! :D, need to use method setValidators from AbstractControl:

  newAccount.controls['msg'].setValidators(Validators.maxLengt‌h(this.maxMsglength)‌​)

Method overites previous validator and set new with updated maxMsgLenth value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.