Awesome Angular 4 form validator routine

One of the things I like the most about Angular is the ability to make even complex forms relatively simple. In Angular 1 I had a library of form helpers that I wrote, the basic idea was initially show a blank form, when user fills in (dirties) an entry it should do validation. When the user click on the submit button it should do validation of all items on the form, submit the form if no errors and show any errors if there were any. This sounds simple enough but in reality it was a few hundred lines of code to do it correctly.

Angular 2+ (Angular 4 on Ionic 3 in this case) make life a lot easier, especially once you’ve got to terms with the FormBuilder framework. To force whole-form validation (including any subforms) simply create a module called form-tools.ts looking like:

// Force a form to show any invalid entries and return if form is valid or not. Recurse through any subforms.
export const validateForm = (form) => {
    Object.keys( form.controls ).forEach( control_name => {
        let control = form.controls[control_name];

        control.markAsTouched();
        if( 'controls' in control )
            validateForm( control );
    });

    return form.valid;
};

Then you can easily use it from another class as follows:

import { FormBuilder } from '@angular/forms';
import { validateForm } from '../../form-tools';

class ...Page {
    constructor(private fb : FormBuilder ) {
        this.userForm = this.fb.group({
            form elements...
        });
    }

    submit_form() {
        if( !validateForm(this.userForm) )
            return;
        send the form request to the server(this.userForm.value)
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *