Url Validation In Angular

Our application might include some fields where the user needs to provide the name of the website that he wants to access, in these cases we require a valid URL of the website from the user, for this we must apply some validation in our form that providing an valid format of URL, this article will help you to apply this validation.

  • In app.component.ts
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) {
    this.myForm = formBuilder.group({
      url: ['', [Validators.required, Validators.pattern('(https?://)?([\\da-z.-]+)\\.([a-z.]{2,6})[/\\w .-]*/?')]]
    })
  }

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

}
  • In app.component.html
<div class="container mt-5 w-25">
    <h4>Pattern URL Validation</h4>
    <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="myForm.get('url')?.touched && myForm.get('url')?.invalid" class="alert alert-danger">
                <div *ngIf="myForm.get('url')?.errors?.['required']">Please provide url</div>
                <div *ngIf="myForm.get('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>

output:

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories