Angular 16 URL Validation using Regular Expression Tutorial

Last updated on: by Digamber

Angular URL pattern validation tutorial; In this quick guide, we will share how to validate a URL in the Angular 16 application using the regular expression.

If you don’t know how to add validation for URL using the regex pattern in the angular application. Fret not! We will explain how to create a form with text input using the reactive forms in angular. This input field will only accept the URL.

After completing this guide, you will have a thorough knowledge of angular URL pattern validation.

This small example will appropriately work well with almost every angular version, be it 8,9,10,11, 12, 13, 14, 15.

Angular Regex Validate URL with Reactive Forms Example

  • Step 1: Install Angular CLI
  • Step 2: Download Angular Project
  • Step 3: Add Reactive Forms Module
  • Step 4: Update TypeScript Template
  • Step 5: Update HTML Template
  • Step 6: Start Angular App

Install Angular CLI

In the first step, you have to install the Angular command-line interface (CLI). Type command and hit enter to begin the installation.

sudo npm install -g @angular/cli

Download Angular Project

Next, you have to install a new angular project, you require to type and execute the following command.

ng new ng-demo

After you ran the suggested command, it will generate a skeleton project within the folder ng-demo with a bunch of files.

Head over to the app’s project directory.

cd ng-demo

To resolve error:

No Property Access From Index Signature:

This setting makes sure profound consistency between accessing a field via the “dot” (obj.key) syntax, and “indexed” (obj["key"]) and the way which the property is declared in the type.

Without this flag, TypeScript will allow you to use the dot syntax to access fields which are not defined:

Make sure to set noPropertyAccessFromIndexSignature property to false under compilerOptions in tsconfig.json file:

"compilerOptions": {
// ...
// ...
   "noPropertyAccessFromIndexSignature": false,
// ...
// ...
}

Add Reactive Forms Module

In further step, you require to import reactive forms module, hence go to src/app/app.module.ts and and add the provided 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 {}

Update TypeScript Template

In this step, you have to import FormBuilder, FormGroup, Validators from ‘@angular/forms’, then define the form using the FormGroup and use the mobile number pattern using the regex and bind it to submit method.

So, open and update 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.scss']
})
export class AppComponent {
  
  public myForm: FormGroup;
  
  constructor(private formBuilder: FormBuilder) {
    this.myForm = formBuilder.group({
      url: ['', [Validators.required, Validators.pattern('(https?://)?([\\da-z.-]+)\\.([a-z.]{2,6})[/\\w .-]*/?')]]
    })
  }
    
  get m(){
    return this.myForm.controls;
  }
   
  onSubmit(){
    console.log(this.myForm.value);
  }
  
}

Update HTML Template

In this step you have to update the HTML template, open the src/app/app.component.html file, create the form using reactive form directive, also define the required validation with url regex pattern validation.

<div class="container mt-5">
  <h2>Angular Pattern URL Validation Example</h2>
  <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">Please provide valid url</div>
      </div>
    </div>
    <div class="d-grid mt-3">
      <button class="btn btn-dark" [disabled]="!myForm.valid" type="submit">Store</button>
    </div>
  </form>
</div>

Start Angular App

Now, you must start the app development server using the given command, make sure to run the following command.

ng serve

If you somehow meets with the following error:

Property ‘xxxName’ comes from an index signature, so it must be accessed with [‘xxxName’]

Ensure that you set the noPropertyAccessFromIndexSignature property to false:

"compilerOptions": {
// ...
// ...
   "noPropertyAccessFromIndexSignature": false,
// ...
// ...
}

Open browser and use the given url to view the app.

http://localhost:4200

Angular 12 URL Validation using Regular Expression Tutorial

Conclusion

In this Angular URL pattern validation example, we have demonstrated how to use the HTML text input element and implement URL validation using the regular expression concerning the angular reactive forms.

positronX.io - Tamso Ma Jyotirgamaya
Digamber

A Full-stack developer with a passion to solve real world problems through functional programming.