【发布时间】:2017-03-16 11:25:06
【问题描述】:
在我的输入字段验证中,我将输入类型设置为“url”。
具有“http://”或“https://”协议的 URL 有效。 没有它,url是无效的。
无效:www.foo.com
无效:foo.com
在我的代码中,每当一个 URL 链接没有“http://”或“https://”时,一个函数“checkURL()”就会像下面的代码一样添加它。
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myform" ).validate({
rules: {
field: {
required: true,
url: true
}
}
});
function checkURL(url) {
var string = url.value;
if (!~string.indexOf("http")) {
string = "http://" + string;
}
url.value = string;
return url;
}
<form id="myform">
<label for="field">Required, URL: </label><br>
<input type="url" id="field" name="field" onblur="checkURL(this)">
</form>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>
在 sn-p 上,我输入“www.yahoo.com”。
当我在字段外单击时,函数 checkURL 会在我的输入中添加“http://”,因此我会得到“http://www.yahoo.com”。
问题是添加“http://”后,jQuery 验证仍然认为 URL 无效。
我必须单击输入字段,然后再次在其外部单击以使其知道它是有效的。
在我们输入一个没有协议的 url(即:www.yahoo.com)后,有没有办法使验证有效?
编辑:我忘记在输入字段中输入我的代码type="url"。
不应更改为 type="text"
【问题讨论】:
-
@Dekel 我忘了为输入标签添加 type="url" 。您给我的链接仅在类型设置为“文本”时才有效,但是当它设置为“url”时,代码无法更新该字段并且仍然将 www.site.com 或 site.com 视为错误。
标签: jquery validation http url input