使用HTML5网址输入验证假设网址以http://开头 [英] With HTML5 url input validation assume url starts with http://

查看:131
本文介绍了使用HTML5网址输入验证假设网址以http://开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML5提供自动网址验证: -

 < form> 
< input type =urlname =someUrl>
< / form>

这将无法验证没有协议前缀的网址 - 例如 stackoverflow.com 会失败,而 http://stackoverflow.com 会通过。



如果没有协议,我该如何自动添加http://到url?



我可以添加一个onblur事件处理函数但有没有更好的方法,像验证事件之前的一些?

解决方案

此代码不应该中断用户的操作,但应该而是等到用户离开表单字段以检查http的输入文本。因此,使用onblur而不是onkeyup。

然后,使用indexOf查看字符串是否包含http。如果不是,它将返回-1,这是falsey。



function checkURL(abc){var string = abc.value; if(!〜string.indexOf(http)){string =http://+ string; } abc.value = string;返回abc}

< form> < input type =urlname =someUrlonblur =checkURL(this)/> < input type =text/>< / form>

小提琴


HTML5 provides for automatic URL validation :-

<form>
   <input type="url" name="someUrl">
</form>

This will fail validation for URL's that don't have a protocol prefix - e.g. stackoverflow.com will fail while http://stackoverflow.com will pass.

How can I automatically add http:// to a url if there isn't already a protocol?

I could add a onblur event handler but is there a better way like some before validation event?

解决方案

The code for this should not interrupt the user's action, but should instead wait until the user leaves the form field to check the input text for "http". So use "onblur" instead of "onkeyup".

Then, just see if the string contains "http" using indexOf. If not, it will return -1, which is falsey.

function checkURL (abc) {
  var string = abc.value;
  if (!~string.indexOf("http")) {
    string = "http://" + string;
  }
  abc.value = string;
  return abc
}

<form>
  <input type="url" name="someUrl" onblur="checkURL(this)" />
  <input type="text"/>
</form>

Fiddle

这篇关于使用HTML5网址输入验证假设网址以http://开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆