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.
To check whether the string entered is a valid URL or not we use the validators module in Python. When we pass the string to the method url() present in the module it returns true(if the string is URL) and ValidationFailure(func=url, …) if URL is invalid.
Using java.net.urlurl class to validate a URL. The idea is to create a URL object from the specified String representation. If we do not get exception while creating the object, we return true. Else we return false.
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
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();
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With