Ext JS 4: Custom Word Counter Validation Type

One of my recent Ext JS 4 projects involved defining text areas with limits on the number of words that can be entered by the user.

I solved this problem by implementing a custom validation type (vtype) as illustrated below:

Ext.apply(Ext.form.field.VTypes, {
    wordlimit : function(v, field) {
        
        v = v.replace(/(^\s*)|(\s*$)/gi,"");
        v = v.replace(/[ ]{2,}/gi," ");
        v = v.replace(/\n /,"\n");
	    var words = v.split(' ').length;
        
        var numremaining = field.maxWords - words;
        
        var fieldLabel = field.getFieldLabel();
        
        fieldLabel = fieldLabel.substring(0, fieldLabel.indexOf('(') - 1);
        field.setFieldLabel(fieldLabel + " (" + numremaining + " words remaining" + " )");
        
        
        if (words <= field.maxWords) {
            return true;
        } else {
            return false;
        }
        
    },
    wordlimitText : "You exceeded the maximum number of words"
});

You can apply the vtype to a textarea as illustrated below:

 var config = {
   xtype: 'textareafield',
   fieldLabel: 'Describe yourself (50 word maximum)',
   labelAlign: 'top',
   allowBlank: false,
   name: 'description',
   anchor: '100%',
   resizable: true,
   resizeHandles: 's',
   vtype: 'wordlimit',
   maxWords: 50
 };
 
 panel.add(config);

You can play with the example by clicking here

Enjoy!

2 thoughts on “Ext JS 4: Custom Word Counter Validation Type

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s