Angular URL/Site Validation using Regular Expression and Bootstrap with Reactive Forms

Introduction

In this article, we learn steps to implement URL number validation in the angular app using the angular URL validation pattern and regular expression. Here we validate URLs in Angular with reactive forms. Reactive forms offer a model-driven path for managing form inputs whose values change over time. It explains the steps to create and update an essential form control for URL/Site validation in Angular.

Here, we create a simple dynamic form where you can use a URL validation pattern under the angular application’s component. Steps to add validation for URL using the regex pattern in the angular application. I will explain the steps to create a form with text input using the reactive forms in angular. This input field will only accept the URL.

Note. Before going through this session, please visit my previous article related to Angular applications as mentioned below.

Step 1. Import Reactive Forms Module

Here we import the reactive forms module, open src/app/app.module.ts, and update the code in the file.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, FormsModule, ReactiveFormsModule],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

Step 2. Update TypeScript Template

Here, we import FormBuilder, FormGroup, and Validators from ‘@angular/forms’, then define the form using FormGroup use the URL pattern using the regex, and bind it to the submit method. Add code in src/app/app.component.ts file.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public myForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {
    const reg = '(https?://)?([\\da-z.-]+)\\.([a-z.]{2,6})[/\\w .-]*/?';
    this.myForm = formBuilder.group({
      url: ['', [Validators.required, Validators.pattern(reg)]]
    });
  }

  get m() {
    return this.myForm.controls;
  }

  onSubmit() {
    console.log(this.myForm.value);
  }
}

The URL validation logic is configured here.

constructor(private formBuilder: FormBuilder) {
    const reg = '(https?://)?([\\da-z.-]+)\\.([a-z.]{2,6})[/\\w .-]*/?';
    this.myForm = formBuilder.group({
      url: ['', [Validators.required, Validators.pattern(reg)]]
    })
  }

Step 3. Update HTML File

Here, we create a form using form Group and ngSubmit directives and define the URL input field using the form control name directive. Build the form using reactive form directive, and also define the required validation with url regex pattern validation. Add code in the src/app/app.component.html file.

<div class="card bg-danger text-white">
  <div class="card-body text-center">
    URL/Site Validation Using Angular
  </div>
</div>
  <div class="container mt-5">
    <form [formGroup]="myForm" (ngSubmit)="onSubmit()" novalidate>
      <div class="form-group">
        <label>Enter URL: </label>
        <input type="text" formControlName="url" class="form-control mb-2">
      <div *ngIf="m.url.touched && m.url.invalid" class="alert alert-danger">
        <div *ngIf="m.url.errors?.required">Please provide URL</div>
        <div *ngIf="m.url.errors?.pattern">Entered URL is not valid</div>
      </div>
        <div class="toast show"
        style="position:fixed;
               top: 70%;
               left: 50%;
               width:30em;
               height:10em;
               margin-top: -9em; /*set to a negative number 1/2 of your height*/
               margin-left: -15em; /*set to a negative number 1/2 of your width*/
               border: 1px solid #ccc;
               background-color: #f3f3f3;
               color: red;
               font-weight:900;
               font-size:larger;"
               *ngIf="m.url.touched && m.url.invalid">
               <div class="toast-header">
                URL/Site Validation Using Angular
                <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
              </div>
          <div class="toast-body" *ngIf="m.url.errors?.required">Please provide URL</div>
          <div class="toast-body" *ngIf="m.url.errors?.pattern">Entered URL is not valid</div>
        </div>
      </div>
      <div class="d-grid mt-3">
        <button class="btn btn-primary" [disabled]="!myForm.valid" type="submit">Send Request</button>
      </div>
    </form>
  </div>

Here the validations are 2 types. One is if the URL input field is empty and the other is if the URL is not valid.

<div *ngIf="m.url.touched && m.url.invalid" class="alert alert-danger">
        <div *ngIf="m.url.errors?.required">Please provide URL</div>
        <div *ngIf="m.url.errors?.pattern">Entered URL is not valid</div>
</div>

----------------------------------------------------------------------------

  <div class="toast show"
        style="position:fixed;
               top: 70%;
               left: 50%;
               width:30em;
               height:10em;
               margin-top: -9em; /*set to a negative number 1/2 of your height*/
               margin-left: -15em; /*set to a negative number 1/2 of your width*/
               border: 1px solid #ccc;
               background-color: #f3f3f3;
               color: red;
               font-weight:900;
               font-size:larger;"
               *ngIf="m.url.touched && m.url.invalid">
               <div class="toast-header">
                URL/Site Validation Using Angular
                <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
              </div>
          <div class="toast-body" *ngIf="m.url.errors?.required">Please provide URL</div>
          <div class="toast-body" *ngIf="m.url.errors?.pattern">Entered URL is not valid</div>
   </div>

Here, we call the onSubmit() method using formGroup and ngSubmit directives.

<form [formGroup]="myForm" (ngSubmit)="onSubmit()" novalidate>
----
----
</form>

Step 4. Add Bootstrap to make the page responsive

Add code in the index.html file.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Title Service Example</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
  <app-root></app-root>
</body>
</html>

Step 5. Update tsconfig.json file

Set the noPropertyAccessFromIndexSignature property to false under compiler options in the tsconfig.json file.

{
  "compileOnSave": false,
  "compilerOptions": {
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": false,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,

Note. By default, the property is set to true. If the above property is not set to false, then we get an error while running the Angular application.

The error details: No Property Access From Index Signature.

Property 'url' comes from an index signature, so it must be accessed with ['url'].

Property 'pattern' comes from an index signature, so it must be accessed with ['pattern'].

-----------------

Property '****Name' comes from an index signature, so it must be accessed with ['****Name']

Output

Here, we run the command (ng serve) to start the angular app server.

The result is shown the first time the page loads.

Result of Page loads

Check the URL validation.

URL Validation

How it performs is shown below.

Valid URL work performance

Note. In this Angular URL validation example, I have demonstrated steps to use the HTML text input element and implement URL validation using the regular expression with the angular reactive forms and Bootstrap.

Summary

In this write-up, we have learned the details below.

  • Steps to perform URL validation using the regular expression in Angular.
  • Steps to add validation for URL using the regex pattern in the Angular application.
  • Know about Angular reactive forms.
  • Steps to fix the issue i.e. No Property Access From Index Signature.

Thank You & Stay Tuned For More


Similar Articles