Search code examples
javascripttabulator

How do you limit the maxlength of inputs in an editable table using Tabulator?


When I use the maxLength:5 validator, no maxlength attribute is applied to the <input /> so users can go over the limit. Is is possible to just limit their input directly, instead of allowing them to break the rules and then having to explain to them what went wrong?

I think this would be better UX in general, and easier for both users and developers.

Also, I tried to add the maxlength to the <input /> manually using some of the callbacks, but it seems like the input isnt created when any of them fire.

Edit: here is the code we're using:

    var table = new Tabulator("#datatable", {
        height: "480px", // set height of table (in CSS or here), this enables the Virtual DOM and improves render speed dramatically (can be any valid css height value)
        layout: "fitDataFill",
        columns: [{ "field": "ID", "frozen": true, "title": "ID", "validator": [] },
        { "editor": "input", "field": "NameEN", "validator": ["maxLength:5"] }],
        addRowPos: "top",
        cellEdited: function (cell) {
            cell.validate();
            var element = cell.getElement();
            $(element).addClass('edited-cell');
            dispatch(actions.EDIT_DATA);
        },
        validationMode: "blocking",
        validationFailed: function (cell, value, validators) {
            var validationMessages = "";
            validators.forEach((validator) => {
                var message = $('#validation-' + validator.type).val() + "\n";
                validationMessages += message.replace('{value}', validator.parameters);
            });
            //cell - cell component for the edited cell
            //value - the value that failed validation
            //validatiors - an array of validator objects that failed
        },
        headerFilter: true
    });

Solution

  • The validation and editing systems in tabulator are totally separate. Validators in Tabulator do not affect the editor, they are applied once a value has been set.

    Once the value on the editor has been submited, in this case by the cell loosing focus, it is then submitted to the validator function, if it passes then the change is made, if it fails then the cell flagged to the user as invalid and the focus passed back onto the cell so they can correct their error.

    If you want to physically prevent a user from entering more then 5 characters then you need to set this on the editor:

    {field:"NameEN", editor:"input", editorParams:{
        elementAttributes:{
            maxlength:"10", //set the maximum character length of the input element to 10 characters
        }
    }}