Upgrade to ExtJS 3.3.1 - Released 11/30/2010
[extjs.git] / src / widgets / form / TextField.js
1 /*!
2  * Ext JS Library 3.3.1
3  * Copyright(c) 2006-2010 Sencha Inc.
4  * licensing@sencha.com
5  * http://www.sencha.com/license
6  */
7 /**
8  * @class Ext.form.TextField
9  * @extends Ext.form.Field
10  * <p>Basic text field.  Can be used as a direct replacement for traditional text inputs,
11  * or as the base class for more sophisticated input controls (like {@link Ext.form.TextArea}
12  * and {@link Ext.form.ComboBox}).</p>
13  * <p><b><u>Validation</u></b></p>
14  * <p>The validation procedure is described in the documentation for {@link #validateValue}.</p>
15  * <p><b><u>Alter Validation Behavior</u></b></p>
16  * <p>Validation behavior for each field can be configured:</p>
17  * <div class="mdetail-params"><ul>
18  * <li><code>{@link Ext.form.TextField#invalidText invalidText}</code> : the default validation message to
19  * show if any validation step above does not provide a message when invalid</li>
20  * <li><code>{@link Ext.form.TextField#maskRe maskRe}</code> : filter out keystrokes before any validation occurs</li>
21  * <li><code>{@link Ext.form.TextField#stripCharsRe stripCharsRe}</code> : filter characters after being typed in,
22  * but before being validated</li>
23  * <li><code>{@link Ext.form.Field#invalidClass invalidClass}</code> : alternate style when invalid</li>
24  * <li><code>{@link Ext.form.Field#validateOnBlur validateOnBlur}</code>,
25  * <code>{@link Ext.form.Field#validationDelay validationDelay}</code>, and
26  * <code>{@link Ext.form.Field#validationEvent validationEvent}</code> : modify how/when validation is triggered</li>
27  * </ul></div>
28  * 
29  * @constructor Creates a new TextField
30  * @param {Object} config Configuration options
31  * 
32  * @xtype textfield
33  */
34 Ext.form.TextField = Ext.extend(Ext.form.Field,  {
35     /**
36      * @cfg {String} vtypeText A custom error message to display in place of the default message provided
37      * for the <b><code>{@link #vtype}</code></b> currently set for this field (defaults to <tt>''</tt>).  <b>Note</b>:
38      * only applies if <b><code>{@link #vtype}</code></b> is set, else ignored.
39      */
40     /**
41      * @cfg {RegExp} stripCharsRe A JavaScript RegExp object used to strip unwanted content from the value
42      * before validation (defaults to <tt>null</tt>).
43      */
44     /**
45      * @cfg {Boolean} grow <tt>true</tt> if this field should automatically grow and shrink to its content
46      * (defaults to <tt>false</tt>)
47      */
48     grow : false,
49     /**
50      * @cfg {Number} growMin The minimum width to allow when <code><b>{@link #grow}</b> = true</code> (defaults
51      * to <tt>30</tt>)
52      */
53     growMin : 30,
54     /**
55      * @cfg {Number} growMax The maximum width to allow when <code><b>{@link #grow}</b> = true</code> (defaults
56      * to <tt>800</tt>)
57      */
58     growMax : 800,
59     /**
60      * @cfg {String} vtype A validation type name as defined in {@link Ext.form.VTypes} (defaults to <tt>null</tt>)
61      */
62     vtype : null,
63     /**
64      * @cfg {RegExp} maskRe An input mask regular expression that will be used to filter keystrokes that do
65      * not match (defaults to <tt>null</tt>)
66      */
67     maskRe : null,
68     /**
69      * @cfg {Boolean} disableKeyFilter Specify <tt>true</tt> to disable input keystroke filtering (defaults
70      * to <tt>false</tt>)
71      */
72     disableKeyFilter : false,
73     /**
74      * @cfg {Boolean} allowBlank Specify <tt>false</tt> to validate that the value's length is > 0 (defaults to
75      * <tt>true</tt>)
76      */
77     allowBlank : true,
78     /**
79      * @cfg {Number} minLength Minimum input field length required (defaults to <tt>0</tt>)
80      */
81     minLength : 0,
82     /**
83      * @cfg {Number} maxLength Maximum input field length allowed by validation (defaults to Number.MAX_VALUE).
84      * This behavior is intended to provide instant feedback to the user by improving usability to allow pasting
85      * and editing or overtyping and back tracking. To restrict the maximum number of characters that can be
86      * entered into the field use <tt><b>{@link Ext.form.Field#autoCreate autoCreate}</b></tt> to add
87      * any attributes you want to a field, for example:<pre><code>
88 var myField = new Ext.form.NumberField({
89     id: 'mobile',
90     anchor:'90%',
91     fieldLabel: 'Mobile',
92     maxLength: 16, // for validation
93     autoCreate: {tag: 'input', type: 'text', size: '20', autocomplete: 'off', maxlength: '10'}
94 });
95 </code></pre>
96      */
97     maxLength : Number.MAX_VALUE,
98     /**
99      * @cfg {String} minLengthText Error text to display if the <b><tt>{@link #minLength minimum length}</tt></b>
100      * validation fails (defaults to <tt>'The minimum length for this field is {minLength}'</tt>)
101      */
102     minLengthText : 'The minimum length for this field is {0}',
103     /**
104      * @cfg {String} maxLengthText Error text to display if the <b><tt>{@link #maxLength maximum length}</tt></b>
105      * validation fails (defaults to <tt>'The maximum length for this field is {maxLength}'</tt>)
106      */
107     maxLengthText : 'The maximum length for this field is {0}',
108     /**
109      * @cfg {Boolean} selectOnFocus <tt>true</tt> to automatically select any existing field text when the field
110      * receives input focus (defaults to <tt>false</tt>)
111      */
112     selectOnFocus : false,
113     /**
114      * @cfg {String} blankText The error text to display if the <b><tt>{@link #allowBlank}</tt></b> validation
115      * fails (defaults to <tt>'This field is required'</tt>)
116      */
117     blankText : 'This field is required',
118     /**
119      * @cfg {Function} validator
120      * <p>A custom validation function to be called during field validation ({@link #validateValue})
121      * (defaults to <tt>null</tt>). If specified, this function will be called first, allowing the
122      * developer to override the default validation process.</p>
123      * <br><p>This function will be passed the following Parameters:</p>
124      * <div class="mdetail-params"><ul>
125      * <li><code>value</code>: <i>Mixed</i>
126      * <div class="sub-desc">The current field value</div></li>
127      * </ul></div>
128      * <br><p>This function is to Return:</p>
129      * <div class="mdetail-params"><ul>
130      * <li><code>true</code>: <i>Boolean</i>
131      * <div class="sub-desc"><code>true</code> if the value is valid</div></li>
132      * <li><code>msg</code>: <i>String</i>
133      * <div class="sub-desc">An error message if the value is invalid</div></li>
134      * </ul></div>
135      */
136     validator : null,
137     /**
138      * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation
139      * (defaults to <tt>null</tt>). If the test fails, the field will be marked invalid using
140      * <b><tt>{@link #regexText}</tt></b>.
141      */
142     regex : null,
143     /**
144      * @cfg {String} regexText The error text to display if <b><tt>{@link #regex}</tt></b> is used and the
145      * test fails during validation (defaults to <tt>''</tt>)
146      */
147     regexText : '',
148     /**
149      * @cfg {String} emptyText The default text to place into an empty field (defaults to <tt>null</tt>).
150      * <b>Note</b>: that this value will be submitted to the server if this field is enabled and configured
151      * with a {@link #name}.
152      */
153     emptyText : null,
154     /**
155      * @cfg {String} emptyClass The CSS class to apply to an empty field to style the <b><tt>{@link #emptyText}</tt></b>
156      * (defaults to <tt>'x-form-empty-field'</tt>).  This class is automatically added and removed as needed
157      * depending on the current field value.
158      */
159     emptyClass : 'x-form-empty-field',
160
161     /**
162      * @cfg {Boolean} enableKeyEvents <tt>true</tt> to enable the proxying of key events for the HTML input
163      * field (defaults to <tt>false</tt>)
164      */
165
166     initComponent : function(){
167         Ext.form.TextField.superclass.initComponent.call(this);
168         this.addEvents(
169             /**
170              * @event autosize
171              * Fires when the <tt><b>{@link #autoSize}</b></tt> function is triggered. The field may or
172              * may not have actually changed size according to the default logic, but this event provides
173              * a hook for the developer to apply additional logic at runtime to resize the field if needed.
174              * @param {Ext.form.Field} this This text field
175              * @param {Number} width The new field width
176              */
177             'autosize',
178
179             /**
180              * @event keydown
181              * Keydown input field event. This event only fires if <tt><b>{@link #enableKeyEvents}</b></tt>
182              * is set to true.
183              * @param {Ext.form.TextField} this This text field
184              * @param {Ext.EventObject} e
185              */
186             'keydown',
187             /**
188              * @event keyup
189              * Keyup input field event. This event only fires if <tt><b>{@link #enableKeyEvents}</b></tt>
190              * is set to true.
191              * @param {Ext.form.TextField} this This text field
192              * @param {Ext.EventObject} e
193              */
194             'keyup',
195             /**
196              * @event keypress
197              * Keypress input field event. This event only fires if <tt><b>{@link #enableKeyEvents}</b></tt>
198              * is set to true.
199              * @param {Ext.form.TextField} this This text field
200              * @param {Ext.EventObject} e
201              */
202             'keypress'
203         );
204     },
205
206     // private
207     initEvents : function(){
208         Ext.form.TextField.superclass.initEvents.call(this);
209         if(this.validationEvent == 'keyup'){
210             this.validationTask = new Ext.util.DelayedTask(this.validate, this);
211             this.mon(this.el, 'keyup', this.filterValidation, this);
212         }
213         else if(this.validationEvent !== false && this.validationEvent != 'blur'){
214                 this.mon(this.el, this.validationEvent, this.validate, this, {buffer: this.validationDelay});
215         }
216         if(this.selectOnFocus || this.emptyText){            
217             this.mon(this.el, 'mousedown', this.onMouseDown, this);
218             
219             if(this.emptyText){
220                 this.applyEmptyText();
221             }
222         }
223         if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Ext.form.VTypes[this.vtype+'Mask']))){
224                 this.mon(this.el, 'keypress', this.filterKeys, this);
225         }
226         if(this.grow){
227                 this.mon(this.el, 'keyup', this.onKeyUpBuffered, this, {buffer: 50});
228                         this.mon(this.el, 'click', this.autoSize, this);
229         }
230         if(this.enableKeyEvents){
231             this.mon(this.el, {
232                 scope: this,
233                 keyup: this.onKeyUp,
234                 keydown: this.onKeyDown,
235                 keypress: this.onKeyPress
236             });
237         }
238     },
239     
240     onMouseDown: function(e){
241         if(!this.hasFocus){
242             this.mon(this.el, 'mouseup', Ext.emptyFn, this, { single: true, preventDefault: true });
243         }
244     },
245
246     processValue : function(value){
247         if(this.stripCharsRe){
248             var newValue = value.replace(this.stripCharsRe, '');
249             if(newValue !== value){
250                 this.setRawValue(newValue);
251                 return newValue;
252             }
253         }
254         return value;
255     },
256
257     filterValidation : function(e){
258         if(!e.isNavKeyPress()){
259             this.validationTask.delay(this.validationDelay);
260         }
261     },
262     
263     //private
264     onDisable: function(){
265         Ext.form.TextField.superclass.onDisable.call(this);
266         if(Ext.isIE){
267             this.el.dom.unselectable = 'on';
268         }
269     },
270     
271     //private
272     onEnable: function(){
273         Ext.form.TextField.superclass.onEnable.call(this);
274         if(Ext.isIE){
275             this.el.dom.unselectable = '';
276         }
277     },
278
279     // private
280     onKeyUpBuffered : function(e){
281         if(this.doAutoSize(e)){
282             this.autoSize();
283         }
284     },
285     
286     // private
287     doAutoSize : function(e){
288         return !e.isNavKeyPress();
289     },
290
291     // private
292     onKeyUp : function(e){
293         this.fireEvent('keyup', this, e);
294     },
295
296     // private
297     onKeyDown : function(e){
298         this.fireEvent('keydown', this, e);
299     },
300
301     // private
302     onKeyPress : function(e){
303         this.fireEvent('keypress', this, e);
304     },
305
306     /**
307      * Resets the current field value to the originally-loaded value and clears any validation messages.
308      * Also adds <tt><b>{@link #emptyText}</b></tt> and <tt><b>{@link #emptyClass}</b></tt> if the
309      * original value was blank.
310      */
311     reset : function(){
312         Ext.form.TextField.superclass.reset.call(this);
313         this.applyEmptyText();
314     },
315
316     applyEmptyText : function(){
317         if(this.rendered && this.emptyText && this.getRawValue().length < 1 && !this.hasFocus){
318             this.setRawValue(this.emptyText);
319             this.el.addClass(this.emptyClass);
320         }
321     },
322
323     // private
324     preFocus : function(){
325         var el = this.el,
326             isEmpty;
327         if(this.emptyText){
328             if(el.dom.value == this.emptyText){
329                 this.setRawValue('');
330                 isEmpty = true;
331             }
332             el.removeClass(this.emptyClass);
333         }
334         if(this.selectOnFocus || isEmpty){
335             el.dom.select();
336         }
337     },
338
339     // private
340     postBlur : function(){
341         this.applyEmptyText();
342     },
343
344     // private
345     filterKeys : function(e){
346         if(e.ctrlKey){
347             return;
348         }
349         var k = e.getKey();
350         if(Ext.isGecko && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
351             return;
352         }
353         var cc = String.fromCharCode(e.getCharCode());
354         if(!Ext.isGecko && e.isSpecialKey() && !cc){
355             return;
356         }
357         if(!this.maskRe.test(cc)){
358             e.stopEvent();
359         }
360     },
361
362     setValue : function(v){
363         if(this.emptyText && this.el && !Ext.isEmpty(v)){
364             this.el.removeClass(this.emptyClass);
365         }
366         Ext.form.TextField.superclass.setValue.apply(this, arguments);
367         this.applyEmptyText();
368         this.autoSize();
369         return this;
370     },
371
372     /**
373      * <p>Validates a value according to the field's validation rules and returns an array of errors
374      * for any failing validations. Validation rules are processed in the following order:</p>
375      * <div class="mdetail-params"><ul>
376      * 
377      * <li><b>1. Field specific validator</b>
378      * <div class="sub-desc">
379      * <p>A validator offers a way to customize and reuse a validation specification.
380      * If a field is configured with a <code>{@link #validator}</code>
381      * function, it will be passed the current field value.  The <code>{@link #validator}</code>
382      * function is expected to return either:
383      * <div class="mdetail-params"><ul>
384      * <li>Boolean <tt>true</tt> if the value is valid (validation continues).</li>
385      * <li>a String to represent the invalid message if invalid (validation halts).</li>
386      * </ul></div>
387      * </div></li>
388      * 
389      * <li><b>2. Basic Validation</b>
390      * <div class="sub-desc">
391      * <p>If the <code>{@link #validator}</code> has not halted validation,
392      * basic validation proceeds as follows:</p>
393      * 
394      * <div class="mdetail-params"><ul>
395      * 
396      * <li><code>{@link #allowBlank}</code> : (Invalid message =
397      * <code>{@link #emptyText}</code>)<div class="sub-desc">
398      * Depending on the configuration of <code>{@link #allowBlank}</code>, a
399      * blank field will cause validation to halt at this step and return
400      * Boolean true or false accordingly.  
401      * </div></li>
402      * 
403      * <li><code>{@link #minLength}</code> : (Invalid message =
404      * <code>{@link #minLengthText}</code>)<div class="sub-desc">
405      * If the passed value does not satisfy the <code>{@link #minLength}</code>
406      * specified, validation halts.
407      * </div></li>
408      * 
409      * <li><code>{@link #maxLength}</code> : (Invalid message =
410      * <code>{@link #maxLengthText}</code>)<div class="sub-desc">
411      * If the passed value does not satisfy the <code>{@link #maxLength}</code>
412      * specified, validation halts.
413      * </div></li>
414      * 
415      * </ul></div>
416      * </div></li>
417      * 
418      * <li><b>3. Preconfigured Validation Types (VTypes)</b>
419      * <div class="sub-desc">
420      * <p>If none of the prior validation steps halts validation, a field
421      * configured with a <code>{@link #vtype}</code> will utilize the
422      * corresponding {@link Ext.form.VTypes VTypes} validation function.
423      * If invalid, either the field's <code>{@link #vtypeText}</code> or
424      * the VTypes vtype Text property will be used for the invalid message.
425      * Keystrokes on the field will be filtered according to the VTypes
426      * vtype Mask property.</p>
427      * </div></li>
428      * 
429      * <li><b>4. Field specific regex test</b>
430      * <div class="sub-desc">
431      * <p>If none of the prior validation steps halts validation, a field's
432      * configured <code>{@link #regex}</code> test will be processed.
433      * The invalid message for this test is configured with
434      * <code>{@link #regexText}</code>.</p>
435      * </div></li>
436      * 
437      * @param {Mixed} value The value to validate. The processed raw value will be used if nothing is passed
438      * @return {Array} Array of any validation errors
439      */
440     getErrors: function(value) {
441         var errors = Ext.form.TextField.superclass.getErrors.apply(this, arguments);
442         
443         value = Ext.isDefined(value) ? value : this.processValue(this.getRawValue());        
444         
445         if (Ext.isFunction(this.validator)) {
446             var msg = this.validator(value);
447             if (msg !== true) {
448                 errors.push(msg);
449             }
450         }
451         
452         if (value.length < 1 || value === this.emptyText) {
453             if (this.allowBlank) {
454                 //if value is blank and allowBlank is true, there cannot be any additional errors
455                 return errors;
456             } else {
457                 errors.push(this.blankText);
458             }
459         }
460         
461         if (!this.allowBlank && (value.length < 1 || value === this.emptyText)) { // if it's blank
462             errors.push(this.blankText);
463         }
464         
465         if (value.length < this.minLength) {
466             errors.push(String.format(this.minLengthText, this.minLength));
467         }
468         
469         if (value.length > this.maxLength) {
470             errors.push(String.format(this.maxLengthText, this.maxLength));
471         }
472         
473         if (this.vtype) {
474             var vt = Ext.form.VTypes;
475             if(!vt[this.vtype](value, this)){
476                 errors.push(this.vtypeText || vt[this.vtype +'Text']);
477             }
478         }
479         
480         if (this.regex && !this.regex.test(value)) {
481             errors.push(this.regexText);
482         }
483         
484         return errors;
485     },
486
487     /**
488      * Selects text in this field
489      * @param {Number} start (optional) The index where the selection should start (defaults to 0)
490      * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
491      */
492     selectText : function(start, end){
493         var v = this.getRawValue();
494         var doFocus = false;
495         if(v.length > 0){
496             start = start === undefined ? 0 : start;
497             end = end === undefined ? v.length : end;
498             var d = this.el.dom;
499             if(d.setSelectionRange){
500                 d.setSelectionRange(start, end);
501             }else if(d.createTextRange){
502                 var range = d.createTextRange();
503                 range.moveStart('character', start);
504                 range.moveEnd('character', end-v.length);
505                 range.select();
506             }
507             doFocus = Ext.isGecko || Ext.isOpera;
508         }else{
509             doFocus = true;
510         }
511         if(doFocus){
512             this.focus();
513         }
514     },
515
516     /**
517      * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
518      * This only takes effect if <tt><b>{@link #grow}</b> = true</tt>, and fires the {@link #autosize} event.
519      */
520     autoSize : function(){
521         if(!this.grow || !this.rendered){
522             return;
523         }
524         if(!this.metrics){
525             this.metrics = Ext.util.TextMetrics.createInstance(this.el);
526         }
527         var el = this.el;
528         var v = el.dom.value;
529         var d = document.createElement('div');
530         d.appendChild(document.createTextNode(v));
531         v = d.innerHTML;
532         Ext.removeNode(d);
533         d = null;
534         v += '&#160;';
535         var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
536         this.el.setWidth(w);
537         this.fireEvent('autosize', this, w);
538     },
539         
540         onDestroy: function(){
541                 if(this.validationTask){
542                         this.validationTask.cancel();
543                         this.validationTask = null;
544                 }
545                 Ext.form.TextField.superclass.onDestroy.call(this);
546         }
547 });
548 Ext.reg('textfield', Ext.form.TextField);