Monday 29 June 2020

Login Form using Template Driven Form with validation

write the following code in Formvalidation.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-formvalidation',
  templateUrl: './formvalidation.component.html',
  styleUrls: ['./formvalidation.component.css']
})
export class FormvalidationComponent {
  City = [
    {id: 1, name: 'Pune'},
    {id: 2, name: 'Mumbai'},
    {id: 3, name: 'Hyderabad'}
  ];

  onSubmit(form) {
    console.log(form.value);
  }
}

write the following code in Formvalidation.html


<div class="container">
    <h2 style="color: cadetblue;">Registration Form</h2>
    <form #form="ngForm" (ngSubmit)="onSubmit(form)" autocomplete="off">
        <div class="form-group">
            <label for="firstName">Name</label>
            <input required id="firstName" type="text" ngModel name="firstName" #firstName="ngModel"  placeholder="Name of Employee" class="form-control">
            <span class="alert alert-danger" *ngIf="firstName.touched && !firstName.valid">
                Name is required
            </span>
        </div>
        <div class="form-group">
            <label for="Password">Password</label>
            <input required minlength="3" maxlength="8" id="Password" type="password" ngModel name="Password" #Password="ngModel" placeholder="Enter Password" class="form-control"
            pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{3,8}$">
            <span class="alert alert-danger" *ngIf="Password.touched && !Password.valid">
                <div *ngIf="Password.errors.required">Password is required</div>
                <div *ngIf="Password.errors.minlength">Minimum {{Password.errors.minlength.requiredLength}} characters are required</div>
                <div *ngIf="Password.errors.pattern">Pattern Not Matched</div>
            </span>
        </div>
        <div class="form-group">
            <label>gender</label>
            <br>
            <input type="radio" ngModel name="Gender" #Gender="ngModel" value="Male" >Male
            <input type="radio" ngModel name="Gender" #Gender="ngModel" value="Female">Female
        </div>
        <div class="form-group">
            <label><input type="checkbox" ngModel name="isSubscribed">Subscribe
            </label>
        </div>
        <div class="form-group">
            <label for="city">Choose City</label>
            <select name="" id="city" class="form-control" ngModel name="city">
                <option value="">Select City</option>
                <option *ngFor="let city of City" [value]="city.id">{{city.name}}</option>
            </select>
        </div>
        <div class="form-group">
            <button class="btn btn-primary" [disabled]="!form.valid">Submit</button>
        </div>
        <div>
            {{form.value | json}}
        </div>
    </form>
</div>


OutPut:




Posted By:  pankaj_bhakre

No comments:

Post a Comment