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