Validate an URL
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
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
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();