HTML5提供自动URL验证: -
<form>
<input type="url" name="someUrl">
</form>
Run Code Online (Sandbox Code Playgroud)
这将无法验证没有协议前缀的URL - 例如,stackoverflow.com在http://stackoverflow.com通过时将失败.
如果还没有协议,如何自动将http://添加到URL?
我可以添加一个onblur事件处理程序,但在验证事件之前有更好的方法吗?
gin*_*nna 18
此代码不应该中断用户的操作,而应该等到用户离开表单字段以检查"http"的输入文本.所以使用"onblur"而不是"onkeyup".
然后,使用indexOf查看字符串是否包含"http".如果没有,它将返回-1,这是假的.
function checkURL (abc) {
var string = abc.value;
if (!~string.indexOf("http")) {
string = "http://" + string;
}
abc.value = string;
return abc
}Run Code Online (Sandbox Code Playgroud)
<form>
<input type="url" name="someUrl" onblur="checkURL(this)" />
<input type="text"/>
</form>Run Code Online (Sandbox Code Playgroud)
如果您不想要浏览器验证(它可能因浏览器而异),您可以添加以下novalidate属性
<input type="url" name="someUrl" formnovalidate="formnovalidate">
Run Code Online (Sandbox Code Playgroud)
否则你可能想要更加透明地为http://添加前缀,只需在有人开始输入时添加,或者甚至将http://已经输入到页面加载的框中
(归功于编辑,他们正确地指出,novalidate适用于表格,而上述优先权,则借记给债权人进行编辑;)
你们可能想要使用的是:
$(function(){
$('input[type="url"]').on('blur', function(){
var string = $(this).val();
if (!string.match(/^https?:/) && string.length) {
string = "https://" + string;
$(this).val(string)
}
});
});
Run Code Online (Sandbox Code Playgroud)
这是在文件准备就绪
检查值是否为空或开头是否缺少http
在模糊的情况下插入它
谢谢@ 1j01
您可以使用
HTML :
<form>
<input type="url" name="someUrl" onkeyup="checkUR(this)" >
</form>
Run Code Online (Sandbox Code Playgroud)
脚本:
function checkUR(abc){
string = abc.value
if(!(/^http:\/\//.test(string))){
string = "http://" + string;
}
abc.value=string
}
Run Code Online (Sandbox Code Playgroud)
我希望它会有所帮助
您可以尝试通过提供初始值和占位符来强制用户输入有效的 url。
<label for="some-url">Some url:</label>
<input id="some-url" type="url" placeholder="http://example.com" value="http://">Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20415 次 |
| 最近记录: |