Validation in Model Driven Forms in Angular2

From Basef
Jump to: navigation, search

Example 1:

In this example there are two fields. The first field uses a combination o two validators. The second field uses only one validator.

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
 
@Component({
    selector: 'my-app',
    templateUrl: 'app/view/my-app.html'
})
 
export class MyAppComponent {
 
    myForm: FormGroup;
 
    constructor() {
        this.myForm = new FormGroup({
            'field1': new FormControl('', [Validators.required, Validators.minLength(6)]),
            'field2': new FormControl('', Validators.required)
        });
    }
 
}

Example 2:

This is a similar to example 1, but uses Form Builder:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
 
@Component({
    selector: 'my-app',
    templateUrl: 'app/view/my-app.html'
})
 
export class MyAppComponent {
 
    myForm: FormGroup;
 
    constructor(private fb: FormBuilder) {
        this.myForm = fb.group({
            'field1': ['', [Validators.required, Validators.minLength(6)]],
            'field2': ['', Validators.required]
        });
    }
 
}