admin

Please wait...

check_circle Form Validation Overview

MediDash provides a comprehensive set of form validation tools to help you build robust and user-friendly forms. This guide will walk you through the process of creating a form with validation, including the necessary dependencies, HTML structure, and component-side code.

extension Dependencies

To create a form with validation, you need to import the following dependencies into your component file:


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

code HTML Structure

The following HTML code demonstrates how to create a form with validation for the first name and last name fields:


<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>

developer_mode Component-Side Code

The following code demonstrates how to create the form group and validators in your component file:


register: FormGroup;

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

link Helpful Resources

For more information on form validation in Angular, please refer to the official documentation:

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

Referral Url

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