0

我有,例如10個輸入。我要檢查,如果他們使用一個規則,但重申避免像這樣空:一個規則來驗證多個輸入與Backbone.validation

firstInput :{ 
    required: true, 
    msg: 'Empty!' 
}, 
// ... 

tenthInput :{ 
    required: true, 
    msg: 'Empty!' 
} 

有沒有使用使用Backbone Validation所有輸入一個規則的方法?每個輸入可以有其他的獨特的驗證規則的同時,如:

firstInput :{ 
    pattern: email, 
    msg: 'Email!!!' 
} 

回答

1

Backbone Validation documentation

// validation attribute can also be defined as a function returning a hash 
var SomeModel = Backbone.Model.extend({ 
    validation: function() { 
    return { 
     name: { 
     required: true 
     } 
    } 
    } 
}); 

然後,你可以調整你的模型有一個函數:

var SomeModel = Backbone.Model.extend({ 
    /** 
    * List of field which are required. 
    * @type {Array|Function} 
    */ 
    required: ['firstInput', 'secondInput', /*...*/ 'tenthInput'], 
    /** 
    * Same format as Backbone Validation 
    * @type {Object|Function} 
    */ 
    specificValidation: { 
     firstInput: { 
      pattern: "email", 
      msg: 'Email!!!' 
     } 
    }, 

    validation: function() { 
     var inputs = _.result(this, 'required'), 
      rules = _.result(this, 'specificValidation'), 
      requiredRule = { required: true, msg: 'Empty!' }; 

     // apply the default validation to each listed field 
     // only if not already defined. 
     _.each(inputs, function(field) { 
      rules[field] = _.defaults({}, rules[field], requiredRule); 
     }); 

     return rules; 
    } 
}); 
+0

關於視圖的綁定是什麼?我做你的榜樣,但'遺漏的類型錯誤:無法讀取屬性「叫」 undefined'的出現 – nllsdfx

+0

@DmitrySoroka它應該工作開箱即用,但也許我忘了的東西或者你正在使用的東西,我不知道,所以該錯誤可能是其他地方。你最好用[mcve]問一個新問題。 –

+0

我想通了! 'specificValidation'的關鍵字可以是包含規則的對象的數組。但是你的'rules [field] = _.defaults({},rules [field],requiredRule)'只處理對象,而不處理對象數組。 – nllsdfx