Ionic 4 - Angular - FormBuilder - Validators

Hello.
Having an issue with validating input fields in Ionic 4, FormBuilder.

I’m using as an example from Josh Morony book - Building Mobile Apps - Lesson 9.

I use FormBuilder to create a FormGroup that has 2 fields in it that map to input fields in the page template. I also add Validators.required to each field in the .ts file.

The data binding portion is working, as I see values typed into the fields appear in log console output. However, no validation occurs… If I leave fields blank, and click button for next page, it just goes on to next page…

So, not sure what I’m missing, but having trouble finding examples of this in Ionic 4.

Code snippets below. Any help appreciated.

home.page.ts:

import {Component} from '@angular/core';
import {Router} from '@angular/router';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

@Component({
    selector: 'app-home',
    templateUrl: 'home.page.html',
    styleUrls: ['home.page.scss'],
})

export class HomePage {

    public loginForm: FormGroup;

    constructor(public router: Router, public formBuilder: FormBuilder) {

        this.loginForm = formBuilder.group({
            username: ['', Validators.required],
            password: ['', Validators.required]
        });

    }

    onSignIn() {
        console.log('what is goin on');
        console.log(this.loginForm.value);
        this.router.navigateByUrl('/referring-physician');
    }

}

home.page.html (portion):

        <form [formGroup]="loginForm">

            <ion-list>
                <ion-item>
                    <ion-label position="stacked">Username</ion-label>
                    <ion-input formControlName="username" type="text">
                    </ion-input>
                </ion-item>


                <ion-item>
                    <ion-label position="stacked">Password</ion-label>
                    <ion-input formControlName="password" type="text">
                    </ion-input>
                </ion-item>

            </ion-list>

            <ion-row class="signin">
                <ion-col>
                    <ion-button (click)="onSignIn()" color="primary" shape="full" expand="block">Sign In</ion-button>
                </ion-col>
            </ion-row>

        </form>

Hi @vvanherk,

If you think about it, clicking the button calls the onSignIn function but there’s nothing telling this function that it shouldn’t navigate if the validation fails.

Try modifying the function to add this check:

onSignIn() {
    if (this.loginForm.invalid) {
      // Show an alert, input hints or something to inform the user the fields are invalid.
      // Let's just return for now
      return;
    }

    this.router.navigateByUrl('/referring-physician');
}

So if the form is invalid, it will return early and not navigate.

Best,
Rodrigo

Hello @FdezRomero.

Thanks for info. That works for prohibiting the navigation.

Follow up question:
What is best approach for having the the validation error message show up on the page - ie: required fields having error message show up in red by input field.

Thanks,

The styling and message of the errors is up to you. Josh also has a blog post about Advanced Forms & Validation in Ionic 2 & 3, where you can see how you can show error messages close to inputs etc.

Some components (like buttons) are used a bit differently in Ionic 4 but it should give you a good idea on how to continue.

@FdezRomero.
Thanks. Will check out that article you referenced.
:beers:

I suppose it’s a matter of opinion, but I prefer disabling the submit button when the form is invalid to throwing an error from inside the submit method, especially when the form is very small, such as we seem to have here.