Here’s the structure I use. It’s not all of the code, but it gives you the idea.
Code:
import { Validators, FormBuilder, FormGroup } from '@angular/forms';
export class MyPage {
form : FormGroup;
// Validation error messages that will be displayed for each form field with errors.
validation_messages = {
'myField': [
{ type: 'pattern', message: 'Please enter a number like 12345678/00.' }
]
}
constructor(public formBuilder: FormBuilder) {
// Create the form and define fields and validators.
this.form = this.formBuilder.group({
myField: ['', Validators.pattern('[0-9]{8}/[0-9]{2}')]
});
// Initial value for the field.
this.form.get('myField').setValue('11223344/55');
}
/*
* Save form values.
*/
save() {
if (this.form.valid) {
// Save your values, using this.form.get('myField').value;
}
}
Template:
<form novalidate [formGroup]="form">
<ion-item>
<ion-label stacked>My Field Label</ion-label>
<ion-input formControlName="myField"></ion-input>
</ion-item>
<div>
<ng-container *ngFor="let validation of validation_messages.myField" >
<div *ngIf="form.get('myField').hasError(validation.type)">
<p>{{validation.message}}</p>
</div>
</ng-container>
</div>
</form>