我已尝试过 documentation 中列出的 custom[function_name] 和 funcCall[methodName] 方法而且我似乎都无法工作。
我的自定义函数如下所示:
function einTest(field, rules, i, options) {
if (field != null) {
var x = field.toString();
if (x.length != 5) {
return options.allrules.ein.alertText2;
}
}
else {
return options.allrules.ein.alertText;
}
}
我在 vaildationEngine-en.js 文件中创建了以下内容:
"ein": {
"alertText": "Not a number.",
"alertText2": "Must be a 5 digit number."
},
我正在尝试在以下 html 字段中使用它:
<tr>
<td><b>Associate Number (EIN):</b></td>
<td><input type="text" id="EIN" name="EIN" class="validate[required,funcCall[einTest]]" data-prompt-position="inline" /></td>
</tr>
但似乎没有任何作用... einTest 函数没有触发。
有什么线索吗?
最佳答案
很可能您没有正确公开该函数。该函数需要限定作用域才能在全局作用域中调用。 “使用第三方函数调用验证字段” documentation ,基本上这意味着它会寻找它的范围与窗口
一起。
所以要做的第一件事就是确保你的函数是公开的。
window.einTest = function(field, rules, i, options) {
接下来要记住的是,该字段实际上是包装该元素的 jquery 对象。因此,为了查看其值或存在等内容,您应该使用 field.val()
if (IsNumeric(field.val())) {
辅助函数
//source: http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
function IsNumeric(input)
{
return (input - 0) == input && (input+'').replace(/^\s+|\s+$/g, "").length > 0;
}
这就是最终结果
html
<p>Enter text in the input and then focus out to see the validation at work.</p>
<b>Associate Number (EIN):</b><br>
<form>
<input type="text" id="EIN" name="EIN" class="validate[required,funcCall[einTest]]" data-prompt-position="inline" />
</form>
js
window.einTest = function(field, rules, i, options) {
if (IsNumeric(field.val())) {
var x = field.val();
if (x.length != 5) {
return options.allrules.ein.alertText2;
}
}
else {
return options.allrules.ein.alertText;
}
};
function IsNumeric(input)
{
return (input - 0) == input && (input+'').replace(/^\s+|\s+$/g, "").length > 0;
}
//plus library initialization
关于jQuery 验证引擎 : Trouble Creating a Custom Function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15484609/