javascript - 使用 jQuery 验证插件对输入进行条件 url 验证

标签 javascript jquery jquery-validate

仅当输入不为空时,我才需要能够验证输入字段是否具有格式正确的 URL。我正在检查输入的值是否不为空,如果是,则验证它是否是一个 URL。然而,这似乎奇怪地破坏了我的代码并且没有验证。

rules: { 
    domain: {
        required: true
    },
    playerClass: {
        required: true,
    },
    if (adTag.value !== '') {  
        url: true
    }
},

完整示例:JSFIDDLE

最佳答案

你正在破坏插件,因为你不能在对象文字中放置条件语句......

rules: {  // <- this is part of an object literal, NOT a function
    domain: {
        required: true
    },
    playerClass: {
        required: true,
    },
    if (adTag.value !== '') {  // <- no good! conditional is outside of a function
        url: true
    }
},

条件语句只能进入函数内部。

rules 选项仅采用以逗号分隔的 key:value 对列表,这些对表示字段 name,其中 value 是它的规则。 然后您可以使用函数来构造规则的参数。

可以做这样的事情......

rules: {
    domain: {
        required: true
    },
    playerClass: {
        required: true,
    },
    adTag: {
        url: function() {
            // conditional statement to return true or false
        }
    }
},
<小时/>

I need to be able to validate an input field ... only if the input is not blank.

如果不使用required规则,这已经是默认行为!

rules: {
    domain: {
        required: true
    },
    playerClass: {
        required: true,
    },
    adTag: {
        url: true  // only gets evaluated when the field is not empty
    }
},

演示:http://jsfiddle.net/bk7x129p/1/

关于javascript - 使用 jQuery 验证插件对输入进行条件 url 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30578847/

相关文章:

javascript - 仅针对被单击的某些链接文本发送警报

javascript - .addClass 只有在无序列表中被点击的元素符号

jquery - 有效方法如果返回 true 则不会清除错误消息

JavaScript - 创建超过 1 个对象时,类事件内部出现 "this"问题

javascript - IE7 什么时候重新计算样式?将类添加到正文时不能可靠地工作

javascript - 对 Google map 进行皮肤处理,使其看起来像原生 Google map iPhone 应用程序

javascript - 如何在新函数中再次使用变量

javascript - 使用 jQuery 禁用无效

jquery - MVC 4 客户端验证不起作用

jquery - MVC4 中不引人注目的客户端验证不起作用