admin

Please wait...

Basic Form Validation

For create form you have to include following dependency in your component file.

                         	
 import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
							
						

HTML code for basic form validation

                         	
<form class="register-form m-4" [formGroup]="register" (ngSubmit)="onRegister()">
    <div class="form-row">
        <div class="form-group col-md-6">
            <label>First name <span class="text-danger">*</span></label>
            <input type="text" class="form-control" placeholder="First name" formControlName="first" required>
            <small class="form-text text-danger"
                *ngIf="!register.get('first').valid && register.get('first').touched">Please
                enter a first name!</small>
        </div>
        <div class="form-group col-md-6">
            <label>Last Name</label>
            <input type="text" class="form-control" placeholder="Last Name" formControlName="last">
            </div>
        </div>
    <div class="form-group">
        <div class="form-check">
          <input class="form-check-input" type="checkbox" formControlName="termcondition">
          <label class="form-check-label">
            I accept terms and conditions
          </label>
        </div>
      </div>
    <div class="row">
      <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 mb-2">
        <button class="btn btn-primary mr-3" [disabled]="!register.valid">Submit</button>
        <button class="btn btn-danger">Cancel</button>
      </div>
    </div>
</form>
							
						

component ts file have following code

                         	
register: FormGroup;
 ngOnInit() {
    this.register = this.fb.group({
        first: ['', [Validators.required, Validators.pattern('[a-zA-Z]+')]],
        last: [''],
        termcondition: [false],
    })
 }
							
						

Referral Url

Type URL
Angular Form Validation https://angular.io/guide/form-validation