使用HTML5 url输入验证假设url以http://开头

Rya*_*yan 23 html5

HTML5提供自动URL验证: -

<form>
   <input type="url" name="someUrl">
</form>
Run Code Online (Sandbox Code Playgroud)

这将无法验证没有协议前缀的URL - 例如,stackoverflow.comhttp://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)

小提琴

  • 不适用于例如`example.com/http`.您应该使用更严格的检查,例如`(string.indexOf("http:")=== 0)`...实际上,这将使它在`http://`之前添加到`https://`urls ,所以更确切地说`(string.match(/ ^ https?:/))`当然,它仍然会将它添加到有效的`ftp://`urls等等.所以如果你想允许任何协议那么它会是`(string.match(/ ^\w +:/))` (11认同)
  • 如果有人只是在输入中使用制表符而不输入任何内容,则此代码是错误的。您只需要使用tab进入下一个字段,现在您不想在url字段中使用一个愚蠢的http:// (2认同)

dov*_*ove 8

如果您不想要浏览器验证(它可能因浏览器而异),您可以添加以下novalidate属性

<input type="url" name="someUrl"  formnovalidate="formnovalidate"> 
Run Code Online (Sandbox Code Playgroud)

否则你可能想要更加透明地为http://添加前缀,只需在有人开始输入时添加,或者甚至将http://已经输入到页面加载的框中

(归功于编辑,他们正确地指出,novalidate适用于表格,而上述优先权,则借记给债权人进行编辑;)


Tos*_*kan 8

你们可能想要使用的是:

$(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


Son*_*dhu 5

您可以使用

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)

例子

我希望它会有所帮助

  • 你只需要`/^https?:/` (4认同)

Vla*_*ovk 5

您可以尝试通过提供初始值和占位符来强制用户输入有效的 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)

  • 对于复制和粘贴以 http://http://example.com 结尾的用户来说,这是一个可靠的方法 (5认同)
  • 这种态度让我将程序员标记为“不要雇用”,无论他们在技术上多么有才华。我们的工作是让各种技能水平的人尽可能轻松地使用网络。 (4认同)