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!
Thanks for the article. The fiddle link isn’t working though.
Try using Sencha Fiddle in Google Chrome.