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.
Depending on your requirements, for example, if you don't want to deal with \ maintain a
RegExp
for an URL, you could delegate the work to the browser's built-in form validation facility.It could be implemented like this:
You can try this way, by slightly modifying and separating your regex:
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