2014-10-17 97 views
3

我一直在尋找一個非常簡單的問題的答案,如何阻止用戶輸入250個字符到Handsontable的單元格?我發現我可以重新創建驗證,但這不會阻止用戶輸入超過250個字符。我正在尋找類似maxlength的東西:Handsontable限制單元格字符

<input id="notes" maxlength="250" /> 



var date_validator_regexp = /(^$|^(0[1-9]|1[012])[/](0[1-9]|[12][0-9]|3[01])[/][0-9]{4}$)/; 
var limit_validator_regexp = /(^[\s\S]{0,250}$)/; 

     $("#gridUpdateNotes").handsontable({ 
      startRows: 1, 
      startCols: 2, 
      colHeaders: ["Date", "Notes"], 
      columnSorting: false, 
      enterBeginsEditing: false, 
      autoWrapRow: true, 
      autoWrapCol: true, 
      minSpareRows: 1, 
      colWidths: [140, 450], 
      removeRowPlugin: true, 
      copyPaste: true, 
      afterValidate: function (isValid, value, row, prop, source) { 
       if (isValid == false && prop === "Notes") { 
        alert("The Notes cannot have more than 250 characters."); 
       } 
      }, 
      columns: [ 
       { 
        data: "NoteDate", 
        type: "date", 
        dateFormat: "mm/dd/yy", 
        allowInvalid: false, 
        validator: date_validator_regexp 
       }, 
       { 
        data: "Notes", 
        allowInvalid: false, 
        validator: limit_validator_regexp 
    } 
      ] 
     }); 

回答

4

這個問題已經過了幾個月了,所以Filjan可能不再需要一個答案。但希望這會幫助別人。

您可以使用函數來代替使用正則表達式作爲驗證程序。

定義列這樣的工作對我來說...

cmlCols = [ 
    { 
     data: "Notes", 
     validator: function (value, callback) { 
      if (value.length > 255) { 
       alert('Must be 255 character or less. Extra characters will be removed'); 
       this.instance.setDataAtCell(this.row, this.col, value.substring(0, 255), null); 
      } 
      callback(true); 
     }]; 
1

我認爲,創建一個新的單元格編輯器似乎是一個更好的方式來處理這個:

(function (Handsontable) { 

'use strict'; 

var MaxLengthEditor = Handsontable.editors.TextEditor.prototype.extend(); 

MaxLengthEditor.prototype.prepare = function() { 
    Handsontable.editors.TextEditor.prototype.prepare.apply(this, arguments); 

    this.TEXTAREA.maxLength = this.cellProperties.maxLength; 
}; 

Handsontable.editors.MaxLengthEditor = MaxLengthEditor; 
Handsontable.editors.registerEditor('maxlength', MaxLengthEditor); 

})(Handsontable); 
+1

關於這個偉大的事情方法與其他答案相比:甚至不允許用戶輸入超出maxLength字符。儘管如此,我仍然無法使用它。從來沒有想出如何設置自定義cellProperties.maxLength,但設法找到一個解決方案,結合這個自定義編輯器和稍微修改後的自定義渲染器。 – 2016-05-19 00:30:09