Confirm the validity of a web address

At the moment, I am utilizing Angular 5 and attempting to validate a URL in the following manner:

Here is the HTML code snippet:

<div class="form-group col-sm-6">
  <input formControlName="s_url" type="url" class="form-control" id="kk" placeholder="url">
  <error-display [displayError]="isValid('s_url')" errMsg="This field is required!"></error-display>
</div>

Within the validate.ts file, you will find this pattern for validation:

s_url: new FormControl('', [
  Validators.required,
  Validators.pattern("/^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/")
]),

However, even when entering a correct URL, an error message still displays due to the pattern.

Answer №1

If you want to improve your regex, consider making slight modifications and separating it into different parts:

const reg = '(https?://)?([\\da-z.-]+)\\.([a-z.]{2,6})[/\\w .-]*/?';
...
Validators.pattern(reg)

Based on personal experience, using quotes (") and slashes (/) directly in the regex could potentially cause issues with the pattern matching when applied to .pattern()


Check out this functional Demo

Answer №2

My revised regex pattern covers more cases:

const urlRegexPattern = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/;
this.form = this.fb.group({
      s_url: ['', [Validators.required, Validators.pattern(urlRegexPattern)]],
    });

For further testing of the pattern, you can visit here

Answer №3

Utilizing the URL API can be beneficial, especially since it currently has a support rate of 95%. You can check the browser support details here

urlValidation: ValidatorFn = (control: AbstractControl) => {
    let isUrlValid = true;

    try {
      new URL(control.value)
    } catch {
      isUrlValid = false;
    }

    return isUrlValid ? null : { invalidUrl: true };
  }

  inputControl = this.fb.control(null, this.urlValidation);

Answer №4

To meet your specific needs, let's say you prefer not to handle or manage a RegExp for a URL, you have the option to entrust this task to the browser's built-in form validation feature.

You can achieve this by doing the following:

const inputField: HTMLInputElement = document.createElement("input");
inputField.type = "url";
inputField.value = value;
const isValidURL: boolean = inputField.checkValidity();

Answer №5

Compatible with all web browsers using the new URL() standard URL validator. This function creates and retrieves a URL object that points to the specified URL by utilizing an absolute URL string or a combination of relative and base URL strings.

function checkValidUrl(input) {
    let isValid = true;
    try {
        if (input) {
           let urlObject = new URL(input);
           if(urlObject.host == "" && urlObject.origin == "null"){
            isValid = false;
           }
        }
    } catch {
        isValid = false;
    }
    return isValid ? null : { invalidUrl: true };
}

Answer №6

I experimented with several regular expressions to validate a URL that I knew was correct, but none of them seemed to work. However, since browsers are already capable of parsing URLs, I opted to create a custom validation function using that API:

export class CustomValidators {
  static validUrl: ValidatorFn = (control: FormControl): ValidationErrors | null  => {
    try {
      let str = control.value;
      if (str.indexOf('://') === -1) {
        str = `https://${str}`;
      }
      const url = new URL(str);
      return null;
    } catch (_) {
      return { invalidUrl: true };
    }
  }
}

You can then use it just like any of the built-in validators:

this.fb.group({
  url: ['', [CustomValidators.validUrl]]
})

Answer №7

Follow this simple method.

Start by downloading and installing the ng2-validation library.

npm install ng2-validation --save

Remember to inject it in your code. Import the library into your app.module.ts file under the import array section

import { CustomFormsModule } from 'ng2-validation'

Make sure to include it in the import array as well,

imports: [BrowserModule, FormsModule, CustomFormsModule],

Next, update your code as shown below

<div class="form-group col-sm-6">
  <input formControlName="s_url" type="url" class="form-control" id="kk" url placeholder="url">

  <div *ngIf="imageUrl.touched && imageUrl.invalid" >
     <div *ngIf="imageUrl.errors.required"> This field is required!</div>
     <div *ngIf="imageUrl.errors.url"> invalid URL </div>
  </div>

</div>

Answer №8

Try using the following regular expression: /^(http[s]?://){0,1}(www\.){0,1}[a-zA-Z0-9\.-]+\.[a-zA-Z]{2,5}\.{0,1}/

This regex pattern is designed to match various types of URLs

Answer №9

Specifically for URLs with the www prefix:

  • www.yahoo.com - correct

  • yahoo.com - incorrect

  • - Incorrect

    (www)\\.([\\da-z.-]+)\\.([a-z.]{2,6})[/\\w .-]*/?

Answer №10

If you are in search of a regular expression that verifies whether a URL starts with "https" but not with "http" or any other variation, and allows for queries and all types of URLs, look no further:

/^https:\/*(?:\w+(?::\w+)?@)?[^\s\/]+(?::\d+)?(?:\/[\w#!:.?+=&%@\-\/]*)?$/

You can utilize the following website to customize it according to your requirements: https://regex101.com/

Answer №11

/**
 * The regular expression provided here is designed to identify URLs that begin with optional protocols (http://, https://, or ftp://),
 * followed by a domain name, domain extension, and a variety of characters that make up the path, query, or fragment portion of
 * the URL. It also allows for `%` as a valid character (for encoded characters).
 *
 * Reference: https://regexr.com/7q3qi
 */
const CUSTOM_URL_PATTERN: RegExp = /^(?:(?:http|https|ftp):\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-._~:/?#[\]@!$&'()*+,;=%]+$/;

Answer №12

Here is a regular expression you can use:

/^((http|https|ftp|www):\/\/)?([a-zA-Z0-9\~\!\@\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)(\.)([a-zA-Z0-9\~\!\@\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]+)/g

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What might be causing the component in Angular and TypeScript to have trouble reading the data returned by the service?

I've been working on this for hours without success. I created a web API get method that returns a simple array. public Hero[] getHeroes() { return new Hero[] { new Hero { Id = 1, Name = "Hunain Hafeez-1" }, ...

Sorting an array of objects in Typescript using a dynamic property name for generics

My goal is to develop a versatile, typed function that can arrange an array of objects by a numerical value housed under a dynamically named property within each object. Here is my current progress: export const sortByNumber = <T, K extends keyof T> ...

Modify the internal class style to set overflow property to visible for a particular class in PrimeNG

Looking for a way to customize the styles of PrimeNG or Angular2 components? The documentation may be lacking clarity, but you can find more information at this URL: http://www.primefaces.org/primeng/#/dialog So, how do you actually go about changing the ...

Explore the world of watching and references using typescript and vue-property-decorator

I'm inquiring about watches and refs. The situation is that I have a vswitch with a v-model where the setter action takes quite a bit of time to complete (involving writes to the store and numerous updates on the DOM). An issue arises when Vue execut ...

Keycloak Redirect URI Error: Page Not Found

I’ve been trying to integrate keycloak with Angular, but I keep running into the invalid_redirect_uri/Page_not_found error. https://i.sstatic.net/cXoE2.png https://i.sstatic.net/3bcXM.png https://i.sstatic.net/2t03M.png https://i.sstatic.net/7yjCA.pn ...

How to safely install npm packages without overwriting any custom changes made to existing node modules

While developing an angular app, I encountered an error in an external package (e.g. packageA). To address this issue, I made some edits to node_modules/packageA/somescript.js and the app is now functioning correctly. However, every time I run npm install ...

Unable to locate the main source for loading

I am facing an issue with my app where I am unable to load a basic component. It seems like a simple problem, but I just can't seem to figure it out. Here is the code for my component: import { Component, OnInit } from '@angular/core'; imp ...

Sorting custom folders and files in an Angular Material table is a breeze with this handy feature

In my mat-table, I have a mix of Files and Folders that need to be sorted similar to Microsoft's file explorer. Folders should not be separated from other folders, and the same rule applies to files. All other sorting rules should remain unchanged. ...

Odd Behavior when altering button attribute using Jquery

After disabling a button with a click handler, I have noticed an interesting behavior where the button does not submit afterwards. The issue seems to vary between different browsers, with Firefox still allowing form submission after the button is disabled, ...

Encountering an error while unit testing Angular components with MatDialog: "Error: <spyOn>: open has already been spied upon."

Once I create an HTML file with a button, I trigger a poll to appear after an onClick event. Then, when the "submit" button is clicked on the dialog window, it closes and I intend to execute subsequent methods. In my TypeScript file: openDialogWindow() { ...

Validation of Date in Angular 5 (with specified minimum and maximum dates)

Struggling to find a simple solution for this issue, I have a date input like the following: <input [(ngModel)]="toolDate" type="text" class="tool_input tool_input__date"> To control the input and restrict it to only accept dates, I am using . In m ...

Refreshing manually will display only the JSON data

Utilizing a NodeJS server to fetch information from a MySQL database and presenting it as a JSON object is the task at hand. app.get('/random', (req, res) => { var connection = mysql.createConnection({ host: 'localhost', ...

Is 'not set' in Google Analytics indicating the browser version?

I came across a similar question on Stack Overflow, but my situation is unique. After adding the Google Analytics script to my project (Angular4), I noticed that I am receiving all information except for browser information. Some browsers are showing &apo ...

What is the best way to implement a generic parameter with constraints in an abstract method?

Take a look at this scenario: interface BaseArgs { service: string } abstract class BaseClass { constructor(name: string, args: BaseArgs) { this.setFields(args) } abstract setFields<T extends BaseArgs>(args: T): void } interface ChildA ...

Finding a solution to the dilemma of which comes first, the chicken or the egg, when it comes to using `tsc

My folder structure consists of: dist/ src/ In the src directory, I have my .ts files and in dist, I keep my .js files. (My tsconfig.json file specifies "outDir":"dist" and includes 'src'). Please note that 'dist' is listed in my git ...

Identify the appearance of a web component being added to the Document Object

After reading this discussion regarding a web-component I created: <my-vue-web-comp [userId]="1" id="my-component"></my-vue-web-comp> The component functions properly in Angular. How can I determine when the web component h ...

Error: The flash messages cannot be shown upon form submission

I am currently utilizing nodejs, Express, and Angular 6 for my website project. Recently, I implemented a contact form with nodemailer and now I aim to incorporate a flash message to appear on the contact page upon form submission. Data successfully submi ...

What is the best way to simulate mailgun.messages().send() with Jest?

Currently, I am utilizing the mailgun-js Api for sending emails. Instead of a unit test, I've created an integration test. I am now facing the challenge of writing a unit test case for the sendEmail method within the Mailgun class. I am unsure of how ...

The sort icon in PrimeNG TurboTable is not displayed when the default sorting option is activated

When the default sorting option is enabled on PrimeNG's TurboTable, the sort icon is not initially visible upon loading. However, the column header is styled as intended and the data is sorted correctly. The sort icon only appears when I manually clic ...

Matching only the specified Records in an array of Typescript generic objects

Check out this demo: https://tsplay.dev/Nnavaw I am working with an array that has the following structure: Array<{ id?: string; text?: string; date?: Date; }> This conflicts with the current implementation: data: Array<Par ...