Hello Devs,
In this tutorial, we will learn URL Pattern Validation in Angular
In this section, we will use url validation pattern in angular 6, angular 7, angular 8 and angular 9 application.
Follow this step by step guide below.
Solution:
const reg = '(https?://)?([\\da-z.-]+)\\.([a-z.]{2,6})[/\\w .-]*/?';
this.form = fb.group({
url: ['', [Validators.required, Validators.pattern(reg)]]
})
Example:
src/app/app.component.html
<div class="container">
<h1>URL Validation in Angular - rathorji.in</h1>
<form [formGroup]="form" (ngSubmit)="submit()">
<div class="form-group">
<label for="url">URL</label>
<input
formControlName="url"
id="url"
type="text"
class="form-control">
<div *ngIf="f.url.touched && f.url.invalid" class="alert alert-danger">
<div *ngIf="f.url.errors.required">URL is required.</div>
<div *ngIf="f.url.errors.pattern">Please enter valid url.</div>
</div>
</div>
<button class="btn btn-primary" type="submit" [disabled]="!form.valid">Submit</button>
</form>
</div>
src/app/app.component.ts
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators} from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
form: FormGroup = new FormGroup({});
constructor(private fb: FormBuilder) {
const reg = '(https?://)?([\\da-z.-]+)\\.([a-z.]{2,6})[/\\w .-]*/?';
this.form = fb.group({
url: ['', [Validators.required, Validators.pattern(reg)]]
})
}
get f(){
return this.form.controls;
}
submit(){
console.log(this.form.value);
}
}
May this example help you.