gpt4 book ai didi

javascript - 使用 jquery 进行 URL 验证

转载 作者:行者123 更新时间:2023-11-28 10:09:34 24 4
gpt4 key购买 nike

为什么在下面的代码中,这部分代码中的 if(!$(this).val()){... 不起作用,并且此匹配与 http:///www.st,我想要为:http://stackoverflow.com

示例: http://jsfiddle.net/gp9nL/3/

$('.url').keyup(function(){
if (!$(this).val().match(/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \?=.-]*)*\/?$/)){
$(this).css("background", "#ffc4c4");
result = false;
}else {
$(this).css("background", "#FFFFEC");
result = true;
}
if(!$(this).val()){
alert('field is empty')
$(this).css("background", "#FFFFEC");
}
return result;
});

最佳答案

这个

if(!$(this).val())

可能无法正常工作,因为它是在 keyup 上调用的

$('.url').keyup(function(){

因此,输入中总会有一些东西,因为需要击键才能触发 keyup,并且它永远不会评估为空。

编辑

根据评论

What's the solution?

如果您想检查该字段是否为空,请检查focusout

这是您更新的代码:

$('.url').focusout(function(){

if(!$(this).val()){
alert('field is empty')
$(this).css("background", "#FFFFEC");
}
});

你的 fiddle 已更新:http://jsfiddle.net/gp9nL/4/

关于javascript - 使用 jquery 进行 URL 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7652753/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com