April 1st, 2010 by radu

Recently I needed a text field in ExtJS that doesn’t allow user input to start with space. So I thought it would be useful for others as well. I chose to override the original Ext.form.TextField and make all the textfields in the application have this behaviour.

Here is the code for this:

(function(){
    //put all the code in an anonymous function to hide the local variables from the global namespace

    //methods that will be overriden - keep the original
    var originalFilterKeys = Ext.form.TextField.prototype.filterKeys;
    var originalInitEvents = Ext.form.TextField.prototype.initEvents;

    Ext.override(Ext.form.TextField,{

        // private
        filterKeys : function(e){
            var res = originalFilterKeys.apply(this, arguments);

            var cc = String.fromCharCode(e.getCharCode());

            //if the caret is in the first position, and the typed character
            //was space, stop the event
            if (cc == ' ' && (this.getCaretPos(this.el.dom) == 0) ){
                e.stopEvent()
            }

            //the case when the text is selected and the user presses space
            if (cc == ' ' && this.getSelectedText() == this.getValue()){
                //clear value of the text field
                e.stopEvent();
                this.setValue('');
            }

            return res; //return original result
        },

        /**
         * @return String the selected text or '' if none
         */
        getSelectedText: function(){
            var dom = this.el.dom;
            var selected = (dom.value).substring(this.getSelectionStart(), this.getSelectionEnd());

            return selected;
        },

        getSelectionStart: function(){
            var input = this.el.dom
            if (input.setSelectionRange){ // Mozilla
                return input.selectionStart;
            } else if (document.selection) { // IE
                var pos, textRange = document.selection.createRange().duplicate();

                if (textRange.text.length > 0) { // selection is not collapsed
                    pos = input.value.indexOf(textRange.text);
                } else { // selection is collapsed
                    pos = 0;
                }

                return pos;
            }
            return 0;
        },

        getSelectionEnd: function() {
            var input = this.el.dom
            if (input.setSelectionRange){ // Mozilla
                return input.selectionEnd;
            } else if (document.selection) { // IE
                var selectedRange = document.selection.createRange().duplicate();
                if (selectedRange.text.length > 0){
                    selectedRange.moveStart("character", -input.value.length);
                }
                return selectedRange.text.length;
            }

            return 0;
        },

        /**
         * @return int - the current index of the caret
         */
        getCaretPos: function() {
            var input = this.el.dom;
            var pos = 0;
            if (input.createTextRange) {
                var range = document.selection.createRange().duplicate();
                range.moveStart('textedit',-1);
                pos = range.text.length;
            } else if (input.setSelectionRange) {
                pos = input.selectionEnd;
            }
            return pos;
        },

        // private
        initEvents : function(){
            this.maskRe = new RegExp('.*'); //I just needed a reg exp to match all characters
            //as filterKeys method is only called if the textfield has a 'maskRe' property
            return originalInitEvents.call(this);
        }
    })

})()

Hope it helps! Enjoy the code. If you have any questions, let me know!

4 Responses to “ExtJS TextField that cannot start with whitespace”
Albert says:

You can use regular expressions to filter the input and validate. use vtype

Sergiu says:

Salut Radu,
Incerc sa formez o comunitate a programatorilor romani in EXTJS. Daca vrei, poti sa ni te alaturi pe facebook: http://www.facebook.com/group.php?gid=264882429228&ref=ts. Daca ai nevoie de ajutor vreodata, nu ezita sa ma contactezi: sergiu_em@yahoo.com

radu says:

Salut Sergiu,

buna initiativa, sunt pentru. Eu nu folosesc Facebook, dar daca vor fi si alte forme de exprimare in comunitate, sa ma anunti.

Sergiu says:

Salut,
Deocamdata, suntem doar pe facebook si nu suntem foarte multi. Poate in viitor ne vom inmulti. In functie de timpul disponibil voi incerca sa creez un forum. O sa te anunt, daca reusesc:)

Leave a Reply