Imagine building an application where users need to enter URLs or website addresses, and you want to ensure these links are valid before processing them. It’s frustrating when users get errors due to invalid URLs, and the best way to avoid this is to implement proper URL validation. In this guide, we will walk you through the process of validating URLs in Angular using regular expressions (regex), integrating them with Bootstrap for a stylish UI, and utilizing Angular’s reactive forms for an optimized user experience. If you’re a web developer looking to improve form validation in your Angular projects, you’re in the right place.
In this article, we will cover everything from setting up Angular reactive forms to writing the perfect regular expression for URL validation. Let’s dive into the process!
Why Angular URL Validation is Crucial?
Before jumping into the technical details, it’s important to understand why URL validation matters. When users input URLs into your app, the risk of malformed or incorrect URLs can lead to broken links, invalid data submissions, or even application crashes. Validating URLs ensures that the data submitted is correct, helping you avoid errors down the line.
Moreover, when combined with the elegance of Bootstrap for UI and Reactive Forms for better control over form behavior, your validation becomes a smooth and intuitive process, making your app more user-friendly.
You can view and download the full working demo on Stackblitz.
Setting Up Angular Environment
Step 1: Install Angular CLI
To get started, you first need to install Angular CLI if you haven’t done so already. Angular CLI is a command-line interface tool that helps in setting up Angular applications and managing their configurations.
npm install -g @angular/cli
Step 2: Create a New Angular Project
Once the installation is complete, create a new Angular project by running:
ng new angular-url-validation
Navigate into the project folder:
cd angular-url-validation
Step 3: Install Bootstrap
Bootstrap makes it easy to style forms and UI components, so let’s add it to our project. You can install Bootstrap by running:
npm install bootstrap
After installation, open the angular.json
file and add Bootstrap’s CSS link in the styles
array.
"styles": [ "src/styles.css", "node_modules/bootstrap/dist/css/bootstrap.min.css" ]
Step 4: Create a Reactive Form in Angular
In Angular, Reactive Forms offer a powerful approach to handling form controls and validations. Here, we will create a simple form that allows the user to input a URL.
First, import ReactiveFormsModule
in your app’s main module (app.module.ts
):
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule, ReactiveFormsModule], providers: [], bootstrap: [AppComponent] }) export class AppModule {}
Next, in the app.component.ts
file, create the form group and define the URL validation logic.
import { Component } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { urlForm: FormGroup; constructor(private fb: FormBuilder) { this.urlForm = this.fb.group({ url: ['', [Validators.required, Validators.pattern(/^https?://[^s$.?#].[^s]*$/i)]] }); } get url() { return this.urlForm.get('url'); } onSubmit() { if (this.urlForm.valid) { alert('URL is valid!'); } else { alert('Please enter a valid URL.'); } } }
Here, we’re using Angular’s FormBuilder to create a reactive form. The url field has two validators:
Validators.required
ensures that the field is not empty.Validators.pattern
uses a regular expression to match valid URLs. The regex/^https?://[^s$.?#].[^s]*$/i
ensures the URL starts withhttp://
orhttps://
.
Step 5: Design the Form with Bootstrap
Now, let’s design the form in app.component.html
using Bootstrap to give it a clean and responsive look.
<div class="container"> <h1 class="text-center my-4">URL Validation Form</h1> <!-- Reactive form --> <form [formGroup]="urlForm" (ngSubmit)="onSubmit()"> <div class="mb-3"> <label for="url" class="form-label">Enter URL</label> <input type="text" id="url" class="form-control" formControlName="url" placeholder="https://example.com" /> <div *ngIf="url?.touched && url?.invalid" class="text-danger mt-2"> <small *ngIf="url?.hasError('required')">URL is required.</small> <small *ngIf="url?.hasError('pattern')"> Please enter a valid URL starting with http:// or https:// </small> </div> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> <!-- Form status message (success or error) --> <div *ngIf="formStatusMessage" class="mt-4"> <div [ngClass]="formStatusClass" role="alert"> {{ formStatusMessage }} </div> </div> </div>
In this code:
We use Bootstrap classes like
form-control
,form-label
, andbtn
for styling.The
*ngIf
directive is used to show error messages if the user touches the input field and the URL is invalid.
Testing the URL Validation
Once everything is set up, it’s time to test the URL validation. When the user enters a valid URL (e.g., https://google.com
), the form will be considered valid. If they input an invalid URL, such as htt://google
or leave the input empty, error messages will appear.
You can view and download the full working demo on Stackblitz.
Output:
1. URL Validation Using Regular Expressions demo - success scenario
2. URL Validation Using Regular Expressions demo - failure scenario
Understanding the Regular Expression for URL Validation
Let’s break down the regular expression used for URL validation:
/^https?://[^s$.?#].[^s]*$/i
^https?:
ensures that the URL starts withhttp
orhttps
.//
allows for the double forward slash (//
).[^s$.?#]
matches any character that is not a whitespace or special character..[^s]*
ensures the URL has additional characters and avoids spaces.$
signifies the end of the string.The
i
flag makes the match case-insensitive.
How to Handle Invalid Inputs Gracefully
It’s essential to offer a user-friendly interface for invalid inputs. Using Bootstrap’s alert system, you can display dynamic messages or use tooltips to give helpful hints. Here’s a quick example:
Invalid URL. Please enter a URL starting with http:// or https://
Stay Tuned for More Angular Tips!
Implementing Angular URL validation with regular expressions and Bootstrap isn’t just practical – it makes your forms more user-friendly and your application more reliable. As we dive deeper into Angular, we’ll explore even more advanced validation techniques and UI tricks to make your app even better. Stay tuned for more insights!
FAQs
1. What is URL validation in Angular?
URL validation in Angular ensures that user-submitted URLs are properly formatted and valid. It prevents errors like broken links or incorrect data.
2. How do I validate a URL using regex in Angular?
You can use Angular’s reactive form validation with a regular expression to check if a URL starts with http://
or https://
. This is done using Validators.pattern()
.
3. Can I customize the error messages for invalid URLs in Angular?
Yes, you can customize error messages by using *ngIf
directives in the template and checking for specific validation errors like required
or pattern
.
4. Why is Bootstrap used in Angular forms?
Bootstrap is used for styling forms and UI components quickly and responsively. It helps make your forms look clean and user-friendly with minimal effort.
5. How can I test URL validation in Angular?
To test URL validation, enter valid and invalid URLs into the form and check if the error messages appear correctly when the input is invalid.
You can view and download the full working demo on Stackblitz.
Stay engaged and drop your questions or thoughts in the comments below! Happy coding!
Discover more from 9Mood
Subscribe to get the latest posts sent to your email.
0 Comments