将jQuery Validation插件中的验证方法与“或"组合而不是“和" [英] Combining validation methods in jQuery Validation plugin with "or" instead of "and"
问题描述
在jQuery Validation插件中,有两种方法可以执行相同的操作,但是对于不同的语言环境(例如dateISO
和dateDE
),它们都可以验证日期格式.如何合并这些,以便输入元素接受任一?
In the jQuery Validation plugin there are a couple of methods that do the same thing, but for different locales, for example dateISO
and dateDE
, that both validate date formatting. How do I combine these so that the input element accepts either?
假设我的表单中有一个<input type="text" name="dateInput" id="dateInput" />
,并且我希望允许用户在此字段中仅输入日期.但是,我希望允许使用几种不同的日期格式-例如,用户应该能够输入 ISO日期或根据德国日期规则设置格式的日期.
Let's say I have an <input type="text" name="dateInput" id="dateInput" />
in my form, and I want to allow users to enter only dates in this field. However, I want to allow for several different date formats - for example, the user should be able to enter either an ISO date or a date formatted accoding to German date rules.
如果我愿意
rules: { dateInput: { required: true, dateISO: true, dateDE: true } }
该表格将永远有效,因为这两种日期格式都是必需的,并且永远无法满足该要求.有没有一种方法可以将它们组合为或"而不是与",而无需编写自己的验证方法?
the form will never be valid, as both date formats will be required and that requirement can never be fulfilled. Is there a way to combine these as an "or" instead of as an "and", without having to write my own validation method?
如果我必须自己编写,如何使它尽可能通用?
And if I do have to write my own, how do I make it as generic as possible?
推荐答案
虽然您可以像Reigel一样组合正则表达式,但是也可以直接调用这些方法(以防它们改变!),如下所示:
While you can combine the regexes like Reigel has, you can also just call those methods directly (in case they change!), like this:
$.validator.addMethod("dateISODE", function(value, element) {
return $.validator.methods.dateISO.apply(this, arguments)
|| $.validator.methods.date.apply(this, arguments);
}, "Please enter a valid ISO or German date");
现在我在这里使用的是date
而不是dateDE
,因为在新版本的插件本地化文件中,该文件会覆盖date
方法.如果您使用的是旧版本就可以了,请坚持使用dateDE
.
Now I have date
instead of dateDE
here, because in newer versions of the plugin dateDE
was removed. It's now in a localization file that just overrides the date
method. If you're using an older version that's fine, just stick with dateDE
.
更新评论:更通用的形式如下:
Update for comments: A more generic form would look like this:
$.validator.addMethod("oneOf", function(value, element, params) {
for(p in params) {
if(params.hasOwnProperty(p) &&
$.validator.methods[p].apply(this, [value, element, params[p]]))
return true;
}
return false;
}, "Please enter a valid date");
规则如下:
$("form").validate({
rules: {
dateFieldName: { oneOf: { dateISO:true, date:true } }
}
});
您可以在此处尝试演示,它需要使用任意数量的验证器功能并运行它们,至少必须返回true
才能成功.
You can try a demo here, this takes any number of validator functions and runs them, at least one must return true
for it to succeed.
这篇关于将jQuery Validation插件中的验证方法与“或"组合而不是“和"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!