0

Summary

I am creating a FormControl with a validation pattern. When the pattern is invalid I want to call a function that will display the error message associated with the error that is being thrown.

Example

ngOnInit() {
        this.personalForm = new FormGroup({
            email : new FormControl(this.auth.user.email,Validators.required ),
            first_name: new FormControl(null,[
                Validators.required,
                Validators.pattern("^[a-zA-Zñáéíóúü']{1,30}$")
            ]),
        });
    }

Function to call when input field is not valid.

showError();

Question

Is it possible to call a function if the error is thrown and retrieve the error when an input field is not valid?

wuno
  • 9,547
  • 19
  • 96
  • 180

1 Answers1

1

Use either statusChanges (valid or invalid) or valueChanges event of the FormGroup to do this:

this.personalForm.valueChanges.debounceTime(500).subscribe((data) => {
  if (!this.personalForm.valid) {
    this.showError();
  }
}
Harry Ninh
  • 16,288
  • 5
  • 60
  • 54
  • is statusChanges or valueChanges in the docs somewhere I can read about? Basically when a user leaves the input field I want to call a function if there is an error. – wuno Dec 06 '16 at 01:18
  • They are here https://angular.io/docs/ts/latest/api/forms/index/AbstractControl-class.html To do things when user leaves an input field, you may need to look into `blur` event (something like this http://stackoverflow.com/questions/34918198/how-to-use-onblur-event-on-angular2) – Harry Ninh Dec 06 '16 at 01:49
  • Hey I appreciate you trying to help me. But this really is not working for me. Would you please break this down a little more so I understand it. I have been struggling with this since yesterday. – wuno Dec 06 '16 at 06:52