Skip to content

Commit

Permalink
feat: ✨ add url validator function
Browse files Browse the repository at this point in the history
  • Loading branch information
Hung Pham committed May 18, 2023
1 parent d98e076 commit c8ee3c8
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions projects/ngx-validator/src/lib/validators/validators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {
ValidationErrors,
} from '@angular/forms';

const URL_REGEXP = /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i;

function isObject(arg: any): boolean {
return arg !== null && typeof arg === 'object' && !Array.isArray(arg);
}
Expand Down Expand Up @@ -338,3 +340,13 @@ export function range(range: [number, number], message: string): ValidatorFn {
: null;
};
}

export function url(message: string): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (isEmptyInputValue(control.value) || isEmptyInputValue(range)) {
return null; // don't validate empty values to allow optional controls
}

return URL_REGEXP.test(control.value) ? null : { url: { message } };
};
}

0 comments on commit c8ee3c8

Please sign in to comment.