Tomas Cavataio
Tomas Cavataio

Reputation: 11

Angular dynamic validation only when formControl is invalid

I want the formControl to have a updateOn: 'change' behavior, but only once the user has ended typing and it turns to be invalid.

This is how my formGroup looks like:

  controlValidation = '^((?!-)[A-Za-z0-9-]' + '{1,63}(?<!-)\\.)' + '+[A-Za-z]{2,3}';

  campaignForm: FormGroup = this.formBuilder.group(
    { control: [null, Validators.pattern(this.controlValidation)]},
    { updateOn: 'blur' }
  );

And the template looks something like this

 <div class="form-group">
   <input type="text" formControlName="advertiserDomain" />
   <div *ngIf="campaignForm.get('control').invalid">
      Error message that should only display reactivly BUT only once the user finished writing for the first time
   </div>
</div>

Upvotes: 1

Views: 893

Answers (1)

JSmith
JSmith

Reputation: 4808

I'm not sure to understand the exact meaning of what you are asking but I'll try answer:

Basically the formGroup have no possibilities to know if user starts or ends typing its word or sentence, this is why change is triggered on every changes. Still you could do a hack, considering many characters are typed in a row, you could add a setTimeout that is cancelled when a key is pressed before a certain delay (let say 1 second) and when the delay reaches 1 second use the method updateValueAndValidity() to manually trigger the validity check of your form.

the below code have not been tested but that's the main idea.

your html:

<input type="text" (input)="keyPress()" formControlName="advertiserDomain" />

your ts:

timeout;

keyPress(){

  clearTimeout(this.timeout);

  this.timeout = setTimeout( _ => {
     this.campaignForm.updateValueAndValidity();
  }, 1000);
}

Upvotes: 1

Related Questions