How to URL pattern validation example in Angular | Typescript


In this short tutorial, You will learn about how to do url validation in Angular and typescript application with input form.

This tutorials works all angular versions 2,5,6 8,9,10,11 versions

Other versions available:

URL pattern validation example with reactive forms

First, in application html template component created to display the input form and do the following steps

  • Define the form element with FormGroup directive with urlForm binding
  • Inside form, define input element with formControlName name url
  • validation errors are bound and available with urlForm.controls[url]
  • Validation check added for input box is not empty(errors.required) and focus is in it(touched)
  • if binded errors contains required, displayed error message ‘URL is required’
  • if errors contains pattern, display error message ‘URL format is wrong’
<div>
    <h2>{{ heading | titlecase }}</h2>
    <form [formGroup]="urlForm">
        <input type="text" formControlName="url" />
        <div *ngIf="!urlForm.controls['url'].valid && urlForm.controls['url'].touched">
            <div *ngIf="urlForm.controls['url'].errors.required" style="background-color: red">
                URL is required
            </div>
            <div *ngIf="urlForm.controls['url'].errors.pattern" style="background-color: red">
                URL format is wrong
            </div>
        </div>
    </form>

    <button type="submit ">Submit</button>
</div>

Next, In application controller component, define the logic for regex pattern validation

  • Declared urlForm of type FormGroup which already has an binding to form element.
  • Defined the url regular expression pattern into variable
  • In the constructor, initialized urlForm with new FormControl element ie url
  • these url form control will be bind with input element in html template
  • Validators.required added for not empty validation check
  • Validators.pattern added for url regular expression
  • These validations are checked with blur event `updateOn: blur’ property
import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  heading = 'angular url pattern validation with examples';
  urlForm: FormGroup;

  myusername: string = '';
  urlRegEx =
    '[-a-zA-Z0-9@:%_+.~#?&//=]{2,256}(.[a-z]{2,4})?\b(/[-a-zA-Z0-9@:%_+.~#?&//=]*)?';

  constructor() {
    this.urlForm = new FormGroup({
      url: new FormControl('', {
        validators: [Validators.required, Validators.pattern(this.urlRegEx)],
        updateOn: 'blur',
      }),
    });
  }
  submit() {
    console.log(this.urlForm.value);
  }
}

And output you seen in browser is

Angular URL regex pattern validation example

Angular html5 input type url pattern validation

In modern browsers, Easy approach is to do url pattern validation with inbuilt html5 language

Another way to do url validation is to define the input type=url in html element. However this only supports html5 only and modern browsers.

Input is defined with following attributes

<input type="url" name="websiteurl" id="websiteurl" placeholder="https://example.com" [(ngModel)]="websiteurl" [ngModelOptions]="{ updateOn: 'blur' }" #urlerror="ngModel" pattern="[-a-zA-Z0-9@:%_+.~#?&//=]{2,256}(.[a-z]{2,4})?\b(/[-a-zA-Z0-9@:%_+.~#?&//=]*)?  "

type=url is an input textbox, accepts urls only pattern attribute value is regular expression pattern for url values NgModel directive is to support two way binding from view to controller and viceversa ngModelOptions directive enables to change the behaviour of ngModel value, this will be fired with updateon:blur event.

Following is an complete code

<div>
    <input type="url" name="websiteurl" id="websiteurl" placeholder="https://example.com" [(ngModel)]="websiteurl" [ngModelOptions]="{ updateOn: 'blur' }" #urlerror="ngModel" pattern="[-a-zA-Z0-9@:%_+.~#?&//=]{2,256}(.[a-z]{2,4})?\b(/[-a-zA-Z0-9@:%_+.~#?&//=]*)?  "
        required />
    <div *ngIf="urlerror.invalid && (urlerror.dirty || urlerror.touched)">
        <div *ngIf="urlerror.errors.required">
            <span style="background-color: red">URL is required </span>
        </div>
        <div *ngIf="urlerror.errors.pattern">
            <span style="background-color: red">Invalid URL </span>
        </div>
    </div>
</div>

In the component, just declare input elements name here with default value

import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  heading = 'angular html5 URL pattern validation  example';

  websiteurl: string = '';
}

Typescript url regexp validation

Sometimes, We want to do validation typescript file.

  • It uses same above regular expression pattern for url validation
  • RegExp object is created with regex
  • pattern.test checked against supplied url and return true-valid
  public isValidUrl(urlString: string): boolean {
    try {
      let pattern = new RegExp(this.urlRegEx);
      let valid = pattern.test(urlString);
      return valid;
    } catch (TypeError) {
      return false;
    }
  }
}
}
console.log(this.isValidUrl('https://www.google.com')); // true
console.log(this.isValidUrl('google')); // false

Conclusion

On this post, You learned

  • Angular url pattern validation example with reactive forms
  • HTML 5 input type url form validation
  • Typescript url validation
Similar Posts