'Validate an URL

Currently, I am using Angular 5. I tried to validate an URL as follows:

HTML:

<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>

In validate.ts file, I have this pattern:

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}/")
]),

But with the pattern, error message is shown even when a correct url is typed.



Solution 1:[1]

You can try this way, by slightly modifying and separating your regex:

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

From my own experience the quotes (") and slashes (/) can sometimes cause issues with the regex when passed directly into .pattern()


Here is a working Demo

Solution 2:[2]

Depending on your requirements, for example, if you don't want to deal with \ maintain aRegExp for an URL, you could delegate the work to the browser's built-in form validation facility.

It could be implemented like this:

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

Solution 3:[3]

I think this regex is more complete:

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

Please for pattern check here

Solution 4:[4]

You can also make use of the URL API, which has 95% support at the time of writing this answer. See the browser support here

urlValidator: ValidatorFn = (control: AbstractControl) => {
    let validUrl = true;

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

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

  searchControl = this.fb.control(null, this.urlValidator);

Solution 5:[5]

Use this easy approach..

install this library.

npm install ng2-validation --save

Don't forget this inject this. In your app.module.ts import this to your import array

import { CustomFormsModule } from 'ng2-validation'

And in your import array,

imports: [BrowserModule, FormsModule, CustomFormsModule],

Then modify your code like 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>

Solution 6:[6]

Works in all browsers with new URL() Standard Url validator Creates and returns a URL object referencing the URL specified using an absolute URL string, or a relative URL string and a base URL string.

static url(value) {
    let valid = true;
    try {
        if (value) {
           let validUrl =  new URL(value);
           if(validUrl.host == "" && validUrl.origin == "null"){
            valid = false;
           }
        }
    } catch {
        valid = false;
    }
    return valid ? null : { invalidUrl: true };
}

Solution 7:[7]

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

it works with all kind OF URL

Solution 8:[8]

Only for www prefix url like -

Solution 9:[9]

For anyone looking for a regular expression that checks if starts with "https" and not with "http" or any other way, and accepts "queries" and all sort of urls, here it is:

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

You can use this page if you want to tweak it to your needs: https://regex101.com/

Solution 10:[10]

I tried a half dozen different regexes on a URL I know is valid and none of them worked. But the browser already needs to be able to parse URLs, so I just created a custom validator function with that API, like so:

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 };
    }
  }
}

Then you just use it like one of the built-in validators:

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

Solution 11:[11]

Use this regex

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