1

I have created a registration form and trying to validate it using Angular 5 form's validators. I have gone through other threads on StackOverflow also tried the solution explained in - Angular 5 ngx-bootstrap form validation but i am unable to solve my issue.

My html is -

<div class="was-validated">
  <form [formGroup]="myform" novalidate role="form">
    <div class="row main">
      <div class="main-login main-center" style="padding-top:0px;">
        <form class="form-horizontal" method="post" action="#">
          <div class="row">
            <div class="col-md-5">
              <div class="form-group"
                [ngClass]="{
                'has-success': firstname.valid && (firstname.dirty || firstname.touched),
                'has-danger': firstname.invalid && (firstname.dirty || firstname.touched)
                 }">
                 <label for="firstname" class="cols-sm-2 control-label">First Name</label>
                 <span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"></i></span>
                 <input formControlName="firstname" type="text" class="form-control" name="firstname" id="firstname" placeholder="Enter your First Name" required/>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
  </form>
</div>

My component -

    import { Component, OnInit, Pipe, NgModule } from '@angular/core';
    import { Http } from '@angular/http/src/http';
    import { resetFakeAsyncZone } from '@angular/core/testing';
    import{HttpClient, HttpParams, HttpHeaders} from'@angular/common/http';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/observable/forkjoin';
    import { forkJoin } from 'rxjs/observable/forkJoin';
    import {
             ReactiveFormsModule,FormsModule,FormGroup,FormControl,Validators,FormBuilder
     } from '@angular/forms';
    @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']  
    })
    export class AppComponent implements OnInit {
    myform: FormGroup;
    firstname: FormControl;
    constructor (private http:HttpClient){ }
    ngOnInit(){
    this.createFormControls();
    this.createForm();
    }
    createFormControls(){
    this.firstname= new FormControl('', [Validators.required,
    Validators.pattern("/^[A-Za-z]+$/"), Validators.maxLength(20)])
    }
    createForm(){
    this.myform = new FormGroup({
    firstname: this.firstname
    });
    }
    }

Thanks.

1

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.