验证URL [英] Validate an URL
本文介绍了验证URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当前,我正在使用Angular5.我尝试按以下方式验证URL:
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>
在validate.ts
文件中,我具有以下模式:
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}/")
]),
但是使用此模式,即使键入正确的URL,也会显示错误消息.
But with the pattern, error message is shown even when a correct url is typed.
推荐答案
您可以通过稍微修改和分隔正则表达式来尝试这种方式:
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)
根据我的经验,引号("
)和斜杠(/
)直接传递到.pattern()
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
这篇关于验证URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文