Ilja
Ilja

Reputation: 46547

Validating forms by minlenght, maxlenght, email, number, required etc.. angular 2

I have a sample form in angular

app.html

<form [ngFormModel]="newListingForm" (ngSubmit)="submitListing(newListingForm.value)">

<input type="radio" #typeRadio="ngForm" [ngFormControl]="newListingForm.controls['typeRadio']" value="Event" id="type-event_radio" required>

<input type="radio" #typeRadio="ngForm" [ngFormControl]="newListingForm.controls['typeRadio']" value="Venue" id="type-venue_radio" required>

<input type="text" placeholder="New Title" #mainTitleInput="ngForm" [ngFormControl]="newListingForm.controls['mainTitleInput']" id="main-title_input" class="transparent">

<input type="email" #emailAddressInput="ngForm" [ngFormControl]="newListingForm.controls['emailAddressInput']" id="email-address_input" required>

<!-- etc -->

</form>

app.ts

import {Component} from 'angular2/core';
import {FORM_DIRECTIVES, FormBuilder, ControlGroup, Validators} from 'angular2/common';

@Component({
  templateUrl : 'app/components/new-listing/app.html',
  directives: [FORM_DIRECTIVES]
})

export class NewListingComponent {

  //Helpers
  newListingForm: ControlGroup;

  //Costructor
  constructor(
    fb: FormBuilder
  ){

    //New Listing Form
    this.newListingForm = fb.group({
      'typeRadio': ['', Validators.required],
      'mainTitleInput': ['', Validators.required],
      'emailAddressInput': ['', Validators.required],
    });
  }

  //TODO Form submission
  submitListing(value: string): void {
    console.log("Form Submited");
  }

}

At the moment only validation I see is default one provided by google on required fields. it all goes away. I've been looking into docs and min/max length seems to be easy to implement with my current setup, however there is another interesting asp NG_VALIDATORS Which I think (not sure) provides validation by looking at things like type="email", required etc.. inside a form. Essentially I want to be able to display messages like invalid email this field is required etc.. through angular2..

Upvotes: 1

Views: 269

Answers (2)

Thierry Templier
Thierry Templier

Reputation: 202326

Simply use expression like this (sample with Bootstrap) to leverage attributes (valid or not, errors, ...) of the controls you associated with your inputs:

<form [ngFormModel]="newListingForm">

  <!-- Field name -->
  <div class="form-group form-group-sm"
       [ngClass]="{'has-error':!newListingForm.controls.mainTitleInput.valid}">
    <label for="for"
       class="col-sm-3 control-label">Name:</label>

    <div class="col-sm-8">
      <input [ngFormControl]="newListingForm.controls.mainTitleInput"
             [(ngModel)]="newListing.mainTitleInput"/>
      <span *ngIf="!newListingForm.controls.mainTitleInput.valid"
            class="help-block text-danger">
        <span *ngIf="newListingForm.controls.errors?.required">
          The field is required
        </span>
      </span>
    </div>
  </div>

</form>

With this sample, fields with errors will be displayed in red and error messages is dynamically displayed.

Moreover you add implement custom validators for your fields:

export class CityValidator {
  static validate(control: Control) {
    var validValues = [ 'mycity', ... ];

    var cnt = validValues
      .filter(item => item == control.value)
      .length; 

    return (cnt == 0) ? { city: true } : null;
  }
}

Simply add then into your validators for fields:

this.newListingForm = fb.group({
  'myfield': ['', Validators.compose([
     Validators.required, CityValidator.validate])]
  (...)
});

Hope it helps you, Thierry

Upvotes: 1

Vlado Tesanovic
Vlado Tesanovic

Reputation: 6424

@Ilja you are on good track, improve your code with this:

this.newListingForm = fb.group({
  'typeRadio': ['',  Validators.compose([Validators.required, Validators.minLength(2), Validators.maxLength(40)])],
  'mainTitleInput': ['', Validators.compose([Validators.required, Validators.minLength(2), Validators.maxLength(40)])],
  'emailAddressInput': ['', Validators.compose([Validators.required, Validators.minLength(2), Validators.maxLength(40)])],
});

Consider this example ( with custom email Validator ) https://plnkr.co/edit/5yO4HviXD7xIgMQQ8WKs?p=info

Upvotes: 1

Related Questions