Upgrade to ExtJS 3.0.3 - Released 10/11/2009
[extjs.git] / src / widgets / form / TextField.js
1 /*!
2  * Ext JS Library 3.0.3
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.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(!e.isNavKeyPress()){
282             this.autoSize();
283         }
284     },
285
286     // private
287     onKeyUp : function(e){
288         this.fireEvent('keyup', this, e);
289     },
290
291     // private
292     onKeyDown : function(e){
293         this.fireEvent('keydown', this, e);
294     },
295
296     // private
297     onKeyPress : function(e){
298         this.fireEvent('keypress', this, e);
299     },
300
301     /**
302      * Resets the current field value to the originally-loaded value and clears any validation messages.
303      * Also adds <tt><b>{@link #emptyText}</b></tt> and <tt><b>{@link #emptyClass}</b></tt> if the
304      * original value was blank.
305      */
306     reset : function(){
307         Ext.form.TextField.superclass.reset.call(this);
308         this.applyEmptyText();
309     },
310
311     applyEmptyText : function(){
312         if(this.rendered && this.emptyText && this.getRawValue().length < 1 && !this.hasFocus){
313             this.setRawValue(this.emptyText);
314             this.el.addClass(this.emptyClass);
315         }
316     },
317
318     // private
319     preFocus : function(){
320         var el = this.el;
321         if(this.emptyText){
322             if(el.dom.value == this.emptyText){
323                 this.setRawValue('');
324             }
325             el.removeClass(this.emptyClass);
326         }
327         if(this.selectOnFocus){
328             el.dom.select();
329         }
330     },
331
332     // private
333     postBlur : function(){
334         this.applyEmptyText();
335     },
336
337     // private
338     filterKeys : function(e){
339         // special keys don't generate charCodes, so leave them alone
340         if(e.ctrlKey || e.isSpecialKey()){
341             return;
342         }
343         
344         if(!this.maskRe.test(String.fromCharCode(e.getCharCode()))){
345             e.stopEvent();
346         }
347     },
348
349     setValue : function(v){
350         if(this.emptyText && this.el && !Ext.isEmpty(v)){
351             this.el.removeClass(this.emptyClass);
352         }
353         Ext.form.TextField.superclass.setValue.apply(this, arguments);
354         this.applyEmptyText();
355         this.autoSize();
356         return this;
357     },
358
359     /**
360      * <p>Validates a value according to the field's validation rules and marks the field as invalid
361      * if the validation fails. Validation rules are processed in the following order:</p>
362      * <div class="mdetail-params"><ul>
363      * 
364      * <li><b>1. Field specific validator</b>
365      * <div class="sub-desc">
366      * <p>A validator offers a way to customize and reuse a validation specification.
367      * If a field is configured with a <code>{@link #validator}</code>
368      * function, it will be passed the current field value.  The <code>{@link #validator}</code>
369      * function is expected to return either:
370      * <div class="mdetail-params"><ul>
371      * <li>Boolean <tt>true</tt> if the value is valid (validation continues).</li>
372      * <li>a String to represent the invalid message if invalid (validation halts).</li>
373      * </ul></div>
374      * </div></li>
375      * 
376      * <li><b>2. Basic Validation</b>
377      * <div class="sub-desc">
378      * <p>If the <code>{@link #validator}</code> has not halted validation,
379      * basic validation proceeds as follows:</p>
380      * 
381      * <div class="mdetail-params"><ul>
382      * 
383      * <li><code>{@link #allowBlank}</code> : (Invalid message =
384      * <code>{@link #emptyText}</code>)<div class="sub-desc">
385      * Depending on the configuration of <code>{@link #allowBlank}</code>, a
386      * blank field will cause validation to halt at this step and return
387      * Boolean true or false accordingly.  
388      * </div></li>
389      * 
390      * <li><code>{@link #minLength}</code> : (Invalid message =
391      * <code>{@link #minLengthText}</code>)<div class="sub-desc">
392      * If the passed value does not satisfy the <code>{@link #minLength}</code>
393      * specified, validation halts.
394      * </div></li>
395      * 
396      * <li><code>{@link #maxLength}</code> : (Invalid message =
397      * <code>{@link #maxLengthText}</code>)<div class="sub-desc">
398      * If the passed value does not satisfy the <code>{@link #maxLength}</code>
399      * specified, validation halts.
400      * </div></li>
401      * 
402      * </ul></div>
403      * </div></li>
404      * 
405      * <li><b>3. Preconfigured Validation Types (VTypes)</b>
406      * <div class="sub-desc">
407      * <p>If none of the prior validation steps halts validation, a field
408      * configured with a <code>{@link #vtype}</code> will utilize the
409      * corresponding {@link Ext.form.VTypes VTypes} validation function.
410      * If invalid, either the field's <code>{@link #vtypeText}</code> or
411      * the VTypes vtype Text property will be used for the invalid message.
412      * Keystrokes on the field will be filtered according to the VTypes
413      * vtype Mask property.</p>
414      * </div></li>
415      * 
416      * <li><b>4. Field specific regex test</b>
417      * <div class="sub-desc">
418      * <p>If none of the prior validation steps halts validation, a field's
419      * configured <code>{@link #regex}</code> test will be processed.
420      * The invalid message for this test is configured with
421      * <code>{@link #regexText}</code>.</p>
422      * </div></li>
423      * 
424      * @param {Mixed} value The value to validate
425      * @return {Boolean} True if the value is valid, else false
426      */
427     validateValue : function(value){
428         if(Ext.isFunction(this.validator)){
429             var msg = this.validator(value);
430             if(msg !== true){
431                 this.markInvalid(msg);
432                 return false;
433             }
434         }
435         if(value.length < 1 || value === this.emptyText){ // if it's blank
436              if(this.allowBlank){
437                  this.clearInvalid();
438                  return true;
439              }else{
440                  this.markInvalid(this.blankText);
441                  return false;
442              }
443         }
444         if(value.length < this.minLength){
445             this.markInvalid(String.format(this.minLengthText, this.minLength));
446             return false;
447         }
448         if(value.length > this.maxLength){
449             this.markInvalid(String.format(this.maxLengthText, this.maxLength));
450             return false;
451         }       
452         if(this.vtype){
453             var vt = Ext.form.VTypes;
454             if(!vt[this.vtype](value, this)){
455                 this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
456                 return false;
457             }
458         }
459         if(this.regex && !this.regex.test(value)){
460             this.markInvalid(this.regexText);
461             return false;
462         }
463         return true;
464     },
465
466     /**
467      * Selects text in this field
468      * @param {Number} start (optional) The index where the selection should start (defaults to 0)
469      * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
470      */
471     selectText : function(start, end){
472         var v = this.getRawValue();
473         var doFocus = false;
474         if(v.length > 0){
475             start = start === undefined ? 0 : start;
476             end = end === undefined ? v.length : end;
477             var d = this.el.dom;
478             if(d.setSelectionRange){
479                 d.setSelectionRange(start, end);
480             }else if(d.createTextRange){
481                 var range = d.createTextRange();
482                 range.moveStart('character', start);
483                 range.moveEnd('character', end-v.length);
484                 range.select();
485             }
486             doFocus = Ext.isGecko || Ext.isOpera;
487         }else{
488             doFocus = true;
489         }
490         if(doFocus){
491             this.focus();
492         }
493     },
494
495     /**
496      * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
497      * This only takes effect if <tt><b>{@link #grow}</b> = true</tt>, and fires the {@link #autosize} event.
498      */
499     autoSize : function(){
500         if(!this.grow || !this.rendered){
501             return;
502         }
503         if(!this.metrics){
504             this.metrics = Ext.util.TextMetrics.createInstance(this.el);
505         }
506         var el = this.el;
507         var v = el.dom.value;
508         var d = document.createElement('div');
509         d.appendChild(document.createTextNode(v));
510         v = d.innerHTML;
511         d = null;
512         Ext.removeNode(d);
513         v += '&#160;';
514         var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
515         this.el.setWidth(w);
516         this.fireEvent('autosize', this, w);
517     },
518         
519         onDestroy: function(){
520                 if(this.validationTask){
521                         this.validationTask.cancel();
522                         this.validationTask = null;
523                 }
524                 Ext.form.TextField.superclass.onDestroy.call(this);
525         }
526 });
527 Ext.reg('textfield', Ext.form.TextField);