Handsontable Limit Cell Characters

2019-07-07 01:49发布

I have been searching for the answer to a very simple question, how to stop a user from entering 250 characters into a cell of a Handsontable? I have found I can recreate a validation, but that won't stop a user from entering more than 250 characters. I am looking for something like maxlength:

<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
    }
            ]
        });

2条回答
再贱就再见
2楼-- · 2019-07-07 02:31

I think that creating a new cell editor seems like a better way to approach this:

(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);
查看更多
一纸荒年 Trace。
3楼-- · 2019-07-07 02:32

This question is several months old, so Filjan may no longer need an answer. But hopefully this will help someone out.

Instead of using a regular expression as the validator, you can use a function.

Defining the column like this worked for me...

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);
       }];
查看更多
登录 后发表回答