How to prevent user typing alphabet character on cell

Posted by: ngocnguyen09910060 on 13 April 2023, 7:02 am EST

  • Posted 13 April 2023, 7:02 am EST

    Hi teams,

    On my application, i want to have a cell that only accept numberic character.

    For example:

    1. End user double click to cell A1 => editor is shown with empty value.
    2. End user typing character “123” => editor show “123”.
    3. End user typing character “q” => editor still show “123”.

    Do you have any event that is firing and validating when user is typing real time ?

  • Posted 14 April 2023, 7:31 am EST

    Hello,

    You can stop the user from entering alphabets in the cell editor. For this, you would need to override the isReservedKey() method of GC.Spread.Sheets.CellTypes.Text class. The isReservedKey() method is executed to handle the keyboard events on the cell itself. This method gets the event and context in the arguments. With the event, you can check which key is pressed and if an alphabet key is pressed, you can stop it from entering in editor by using event.preventDefault() method.

    Also, you can use the context obtained in the arguments of isReservedKey() method to determine for which cells the alphabet key should be disabled.

    Please refer to the conde snippet and attached sample which explain the same.

    // overrides the isReservedKey method of Text cell type
    let oldFunction = GC.Spread.Sheets.CellTypes.Text.prototype.isReservedKey;
    GC.Spread.Sheets.CellTypes.Text.prototype.isReservedKey = function (e, context) {
        let code = e.keyCode;
        // checks if the current cell is B2 
        if (context.row === 1 && context.col === 1) {
            // checks if pressed key is alphabet or some special character
            if (!e.ctrlKey && ((code >= 65 && code <= 90) || (code >= 186 && code <= 222))) {
                e.stopImmediatePropagation();
                e.preventDefault();
                return true;
            }
        }
        return oldFunction.apply(this, arguments);
    };
    

    Sample: https://jscodemine.grapecity.com/share/DqN2dODxEUCpKNwH1ljUqw/?defaultOpen={"OpenedFileName"%3A["%2Findex.html"%2C"%2Fsrc%2Fapp.js"]%2C"ActiveFile"%3A"%2Findex.html"}

    Doc references:

    Text.isReservedKey(): https://www.grapecity.com/spreadjs/api/v15/classes/GC.Spread.Sheets.CellTypes.Text#isreservedkey

    GC.Spread.Sheets.CellTypes.Text class: https://www.grapecity.com/spreadjs/api/v16/classes/GC.Spread.Sheets.CellTypes.Text#class-text

    Regards,

    Ankit

Need extra support?

Upgrade your support plan and get personal unlimited phone support with our customer engagement team

Learn More

Forum Channels