【问题标题】:jQuery Validation Engine: Trouble Creating a Custom FunctionjQuery 验证引擎:创建自定义函数时遇到问题
【发布时间】:2013-03-07 05:58:34
【问题描述】:

我已经尝试了列出 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 函数没有触发。

有什么线索吗?

【问题讨论】:

    标签: jquery asp.net-mvc-3 validation jquery-validation-engine


    【解决方案1】:

    jsFiddle Demo

    很可能您没有正确公开该功能。该函数需要限定范围才能在全局范围内调用。 “使用第三方函数调用验证字段”documentation,基本上意味着它会寻找与 window 并列的范围。

    所以首先要做的是确保你的函数是公开的。

    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
    

    【讨论】:

      猜你喜欢
      • 2013-03-02
      • 1970-01-01
      • 1970-01-01
      • 2013-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-01
      • 2017-01-24
      相关资源
      最近更新 更多