2014-10-17 632 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