2012-10-08 60 views
3

我有一個字段,可以包含電子郵件或移動(在我的情況下,手機是8位數字)。 我已經嘗試了兩種方法(兩個示例都不起作用,因爲'元素'沒有驗證方法):jQuery驗證 - 如何驗證一個字段與兩個異或規則

第一種方法:創建自定義方法並在那裏執行兩個驗證,但是接下來我必須創建自己的電子郵件和移動驗證 - 我找不到如何在新方法中重用jQuery驗證規則的方法。這是我想要的:

jQuery.validator.addMethod("mobileoremail", function(value, element) { 
     return this.optional(element) || 
       element.validate({ rules: { digits: true, rangelength: [8, 8] } }) || 
       element.validate({ rules: { email: true } }); 
    }, "Invalid mobile or email"); 

第二種方法:創建依賴規則。而且在這種情況下,我找不到如何重用jQuery驗證規則的方法。

{ myRules: { 
      rules: { 
       user: { 
        required: true, 
        email: { 
         depends: function(element) { 
          return !element.validate({ rules: { mobile: true } }); 
         } 
        }, 
        mobile: { 
         depends: function (element) { 
          return !element.validate({ rules: { email: true } }); 
         } 
        } 
       } 
      } 
     } 
    } 

回答

5

如何以下驗證方法...

$.validator.addMethod("xor", function(val, el, param) { 
    var valid = false; 

    // loop through sets of nested rules 
    for(var i = 0; i < param.length; ++i) { 
     var setResult = true; 

     // loop through nested rules in the set 
     for(var x in param[i]) { 
      var result = $.validator.methods[x].call(this, val, el, param[i][x]); 

      // If the input breaks one rule in a set we stop and move 
      // to the next set... 
      if(!result) { 
       setResult = false; 
       break; 
      } 
     } 

     // If the value passes for one set we stop with a true result 
     if(setResult == true) { 
      valid = true; 
      break; 
     } 
    } 

    // Return the validation result 
    return this.optional(el) || valid; 
}, "The value entered is invalid"); 

然後,我們可以設置表單驗證如下...

$("form").validate({ 
    rules: { 
    input: { 
     xor: [{ 
     digits: true, 
     rangelength: [8, 8] 
     }, { 
     email: true 
     }] 
    } 
    }, 
    messages: { 
    input: { 
     xor: "Please enter a valid email or phone number" 
    } 
    } 
});  

看到它在行動這裏http://jsfiddle.net/eJdBa/

+0

太棒了!優雅的解決方 – marisks

+0

謝謝,它有一個有趣的驗證問題 –

+0

我收到以下錯誤:TypeError:$ .validator.methods [method] is undefined。你有什麼線索爲什麼? 無論如何,很好的解決方案! – Thrasher

相關問題