6/15/16

Form Validation In Angular2

Hi, My today's challenge is to create simple login form, like you can see in almost every web application.
Well, we will use plunker project already created for previous post since it has view called "login". Lets also add css styles of bootstrap library to the project for take advantage of this awesome framework with its form and validtaion styles.

Step 1 - ngModel

Yes, the famous two way data binding is still here. Only now it is using "[(" syntax:


   <form (ngSubmit)="login()">
      <div class="form-group">
        <label for="email">Email</label>
        <input type="text" class="form-control"
          [(ngModel)]="email"
            >
      </div>
      <div class="form-group">
        <label for="password">Password</label>
        <input type="password" class="form-control"
          [(ngModel)]="password"
           >
      </div>

      <button type="submit" class="btn btn-default">Submit</button>
  </form>

lets put simple code of component which only checks the input value is bound correctly:

export class Login {
  public  email: string;
  public  password: string;
  constructor(public router: Router){}
  login(){
    if(this.email && this.password){
       alert(this.email+' '+this.password)
    }
  }
}

Now when some characters filled into both inputs you can see it in alert after clicking submit.

Step 2 - ngForm

It is good practice to use "ngForm" directive which holds the status of form and its controls: The status can be valid (or "invalid"),pristine(or dirty) and touched
By using reference (attribute decorated with "#") and "hidden" directive i can show validation error labels.


 <div class="container">
   
   <form (ngSubmit)="login()">
      <div class="form-group">
        <label for="email">Email</label>
        <input type="text" class="form-control"  required
          [(ngModel)]="email"   ngControl="emailctrl" #emailctrl="ngForm"
            >
        <div [hidden]="emailctrl.valid || emailctrl.pristine" class="alert alert-danger">
          Email is required
        </div>
      </div>
      <div class="form-group">
        <label for="password">Password</label>
        <input type="password" class="form-control"  required
          [(ngModel)]="password"  ngControl="passctrl" #passctrl="ngForm"
           >
        <div [hidden]="passctrl.valid || passctrl.pristine" class="alert alert-danger">
          Passwd is required
        </div>           
      </div>

      <button type="submit" class="btn btn-default">Submit</button>
  </form>
  </div>

From now - if you typing something in one of the controls and then deleting it - the validation messages displayed.

Here is running code: Hope you have fun reading...

No comments:

Post a Comment

Getting started with docker

It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...