Git Product home page Git Product logo

ng-formbuilder's Introduction

Formbuilder Example with validation built with Angular 2 Quickstart template

Some usefull snippets from the code

The form in this example (built with FormBuilder) is reactive form

1. The AppModule app.module.ts

Import:
 import { FormsModule, ReactiveFormsModule } from '@angular/forms';
The NgModule imports array:
  imports:      [ ..., FormsModule, ReactiveFormsModule ],

2. The import statements in the component

I'm not sure if all these imports (FormControl, FormGroup, FormBuilder, Validators and Validators) are necessary. I built this example along tutorial on udemy. But this tutorial worked with a beta release of Angular 2 and just before my self study came the 2.0.0 out. There were braking changes and I had to figure out what works with the the form builder. In the video tutorial they used Control, ControlGroup, FormBuilder, Validators, FORM_DIRECTIVES, ngControl and [ngFormModel].

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

The form it self

In the template:

Use the FormGroup from @angular/forms

<form [formGroup]="form">
and in the class:

first a varibale for the form

form: FormGroup;

and then in the constructor

  this.form = builder.group({
    ...
  });

The form fields

In the template:

With FormControl form @angular/forms

  <input type="text" class="form-control" [formControl]="form.controls['username']" >
and in the class:

The variables for the form fields

  username: FormControl;
  email: FormControl;

And in the constructor for the validation

  this.form = builder.group({
    'username': [the validation parameters],
    'email': [the validation parameters]
  });

The Validation for the form fields

In the template:
  <div *ngIf="form.controls['username'].dirty && !form.controls['username'].pending && !form.controls['username'].valid"> 
    <div *ngIf="!form.controls['username'].required" class="alert alert-danger">Username required</div>
    <div *ngIf="!form.controls['username'].minLength" class="alert alert-danger">Minimum lengt: 3 characters</div>
  </div>
...in the class:
  this.form = builder.group({
    'username': [null, Validators.compose([Validators.required, Validators.minLength(3)])],
    'email': [null, Validators.compose([Validators.required, EmailValidator.invalidEmail])]
  });
          ^   ^   ^   ^   ^   ^   ^   ^   ^   ^   ^   ^   ^   ^   ^   ^   ^   ^   ^  ^   
                                     the validation
...in the helper class emailValidator.ts (file):

Note the regex pattern. There are thousand's different version around, but this works well.

  import { FormControl } from '@angular/forms';

  interface ValidationResult {
    [key: string]: boolean;
  }

  export class EmailValidator {
    static invalidEmail(control: FormControl) {

      let pattern = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9]*[a-z0-9])?/;
      if ( pattern.test( control.value ) ) {
        return null;
      } else {
        return {'invalidEmail': true};
      };
    }
  }

Nice course about Angular 2 Form Validation on scotch.io:

https://scotch.io/tutorials/angular-2-form-validation

ng-formbuilder's People

Contributors

dthuesen avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.