Validate an URL

2019-06-22 11:58发布

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.

2条回答
Juvenile、少年°
2楼-- · 2019-06-22 12:23

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();
查看更多
ゆ 、 Hurt°
3楼-- · 2019-06-22 12:32

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

查看更多
登录 后发表回答