Skip to content

Input Form Validator

Nara77 edited this page Jul 20, 2018 · 8 revisions

**Input Form Validator **

The method we will use makes it easier to manage forms with many fields, and it also allows us to more easily validate data that is entered, this includes:

  • Basic validation using the built-in Angular 2 Validators
  • Custom validation using our own custom validators
  • Multiple validations for a single input field
  • Asynchronous validation (e.g. checking if a username is already taken)

When building forms in Angular 2 it is important to understand what a FormControl is and what a FormGroup is. A FormControl is tied to an input field, it has a value (i.e. the value the user has entered), and a validation state (i.e. whether or not the value is valid based on an optional validation function). A FormGroup is a collection of FormControls.

Form Control Example

this.myControl = new FormControl('value', *validation function goes here*, *asynchronous validation function goes here*);

and this is tied to the input in the template by using the ngControl directive:

<ion-input formControlName="myControl" type="text"></ion-input>

Form Group Example:

    firstName: new FormControl('Josh'),
    lastName: new FormControl('Morony')
});

We could use a Form Builder to make things easier. We use the formBuilder.group function to create our FormGroup by supplying an object containing each of our FormControls. We must also set the formGroup property on the parent

to have the same name as our FormBuilder group, which would look like this:
    firstName: ['value'],
    lastName: ['value', *validation function goes here*],
    age: ['value', *validation function goes here*, *asynchronous validation function goes here*]
});

    <ion-input formControlName="firstName" type="text"></ion-input>
    <ion-input formControlName="lastName" type="text"></ion-input>
    <ion-input formControlName="age" type="number"></ion-input>
</form

To Use FormBuilders the following needs to be imported to the page and contructor:

import { FormBuilder, FormGroup, Validators } from '@angular/forms'; constructor(public navCtrl: NavController, public formBuilder: FormBuilder) {}

For more resources https://ionicframework.com/docs/developer-resources/forms/ https://www.joshmorony.com/advanced-forms-validation-in-ionic-2/ https://medium.com/@daviddentoom/angular-2-form-validation-9b26f73fcb81

Quick Links

Pin useful things here

Home

Clone this wiki locally