Search code examples
angulartypescriptangular2-templateangular2-formsangular2-cli

Model driven forms - Validators issue


I am testing a simple app. These are my files:

home.component.ts

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

@Component({
    selector: 'app-home',
    templateUrl: 'home.component.html'
})
export class HomeComponent {
    form: FormGroup;

    constructor(fb: FormBuilder) {
        this.form = new FormGroup({
            'firstName': new FormControl('', Validators.required),
            'password': new FormControl('', Validators.minLength(5))
        });
    }
    onSubmit() {
        console.log('model-based form submitted');
        console.log(this.form);
    }
}

And this is the template file:

<section class="sample-app-content">
    <h1>Model-based Form Example:</h1>
    <form [formGroup]="form" (ngSubmit)="onSubmit()">
        <div class="form-field">
            <label>First Name:</label>
            <input type="text" formControlName="firstName">
        </div>
   <div class="form-field">
        <label>Password:</label>
        <input type="text" formControlName="password">
   </div>
    <p>
        <button type="submit" [disabled]="!form.valid">Submit</button>
    </p>
</form>

But it is not recognizing the Validators well, because when I write the firstname it enables the submit button, then if I put the firstname in blank, the input never change to red.

What am I doing wrong?

EDIT:

I created a demo here

http://plnkr.co/edit/cs6N0n?p=preview


Solution

  • The angular validator sets the ng-invalid css class if the validation fails. However you haven't defined ng-invalid in your CSS, so you don't get a red border.

    If you define the style in the CSS it works:

    .ng-invalid {
      border-color: #ff0000;
    }
    

    Don't exactly know why the minLength(5) validator for the password allows an empty password. Either it's an angular bug or intended behavior and you need to combine it with the required validator.