How to trigger Angular 2 input validation manually?

JavascriptAngularTypescript

Javascript Problem Overview


I have two inputs:

  • First one on which I apply my custom validator
  • Second one which value I use in my custom validator (it is dynamic and editable)

If I apply my custom validator on the first input, then I focus the second one and change the value - I want to force first inputs re-validation...

At the moment it only re-validates first input when I change the value... Any suggestions?

At the moment when I focus the first input I can access it's reference:

<input
    name="mEnd"
    class="form-control"
    [(ngModel)]="endDate"
       ...
    #endDateInput="ngModel"
    (focus)="clog(endDateInput)"
>

I wonder can I trigger re-validation using the input formControl reference methods?

Javascript Solutions


Solution 1 - Javascript

You can update the validity of a formControl

form.controls['myControl'].updateValueAndValidity();

Solution 2 - Javascript

If you have template-driven form you can access form throw ViewChild decorator:

@ViewChild('myForm') public form: NgForm;

then, validate one field or the whole form group using method mentioned above:

this.form.controls.myControl.updateValueAndValidity();

Solution 3 - Javascript

I found this to be much better

this.myForm.markAllAsTouched();

Solution 4 - Javascript

Angular 12 and the other answers didnt work for me..so i added a hidden button on the form

 <button type="submit" [style.visibility]="'hidden'" #submitBtn>Submit</button>

On the controller ViewChild this button.

  @ViewChild('submitBtn') private buttonSubmit:ElementRef;

And force a click on the event i want.

  submitFormByKey(){
    this.buttonSubmit.nativeElement.click();
  }

This will trigger a submit and validate all.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSlimas SlimanauskasView Question on Stackoverflow
Solution 1 - JavascriptRobin DijkhofView Answer on Stackoverflow
Solution 2 - JavascriptMariia BilykView Answer on Stackoverflow
Solution 3 - JavascriptC.IkongoView Answer on Stackoverflow
Solution 4 - Javascriptcabaji99View Answer on Stackoverflow