[英]Conditional url validation of input with jQuery validate plugin
I need to be able to validate an input field has a correctly formatted URL only if the input is not blank. 仅当输入不为空时,我才需要验证输入字段的URL格式正确。 I am checking whether the value of the input is not blank, and if so, validate that it is a URL.
我正在检查输入的值是否不为空,如果是,请验证它是否为URL。 However, this seems to oddly be breaking my code and not validating.
但是,这似乎奇怪地破坏了我的代码并且没有进行验证。
rules: {
domain: {
required: true
},
playerClass: {
required: true,
},
if (adTag.value !== '') {
url: true
}
},
That's because you are using an expression inside the definition of a JS object. 那是因为您正在JS对象的定义内使用表达式。 This is not possible.
这是不可能的。 You can do this instead:
您可以改为:
rules: {
domain: {
required: true
},
playerClass: {
required: true,
},
adTag: {
url: adTag.value !== ''
}
}
This has a slightly different effect than what you think your code should have as it always creates the url
field, but it will be true
or false
depending whether adTag.value !== ''
is true
. 这比你认为你的代码应该有,因为它总是会创建一个稍微不同的效果
url
字段,但它会是true
还是false
取决于是否adTag.value !== ''
是true
。
You're breaking the plugin, because you cannot put a conditional statement within an object literal... 您正在破坏插件,因为您不能在对象文字中放入条件语句...
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
}
},
A conditional statement can only go inside of a function. 条件语句只能进入函数内部。
The rules
option only takes a comma separated list of key:value
pairs that represent the field name
where the value
is its rules. rules
选项仅采用逗号分隔的key:value
对列表,这些对代表字段name
,其中value
是其规则。 Then you can use a function to construct the parameter for the rule. 然后,您可以使用函数来构造规则的参数。
You could do something like this... 你可以做这样的事情...
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.
我需要能够验证输入字段……仅当输入不为空时。
Without using the required
rule, that is already the default behavior! 不使用
required
规则, 那已经是默认行为!
rules: {
domain: {
required: true
},
playerClass: {
required: true,
},
adTag: {
url: true // only gets evaluated when the field is not empty
}
},
DEMO: http://jsfiddle.net/bk7x129p/1/ 演示: http : //jsfiddle.net/bk7x129p/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.