Upgrade to ExtJS 3.2.2 - Released 06/02/2010
[extjs.git] / src / widgets / form / TextField.js
1 /*!
2  * Ext JS Library 3.2.2
3  * Copyright(c) 2006-2010 Ext JS, Inc.
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(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         if(this.emptyText){
327             if(el.dom.value == this.emptyText){
328                 this.setRawValue('');
329             }
330             el.removeClass(this.emptyClass);
331         }
332         if(this.selectOnFocus){
333             el.dom.select();
334         }
335     },
336
337     // private
338     postBlur : function(){
339         this.applyEmptyText();
340     },
341
342     // private
343     filterKeys : function(e){
344         if(e.ctrlKey){
345             return;
346         }
347         var k = e.getKey();
348         if(Ext.isGecko && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
349             return;
350         }
351         var cc = String.fromCharCode(e.getCharCode());
352         if(!Ext.isGecko && e.isSpecialKey() && !cc){
353             return;
354         }
355         if(!this.maskRe.test(cc)){
356             e.stopEvent();
357         }
358     },
359
360     setValue : function(v){
361         if(this.emptyText && this.el && !Ext.isEmpty(v)){
362             this.el.removeClass(this.emptyClass);
363         }
364         Ext.form.TextField.superclass.setValue.apply(this, arguments);
365         this.applyEmptyText();
366         this.autoSize();
367         return this;
368     },
369
370     /**
371      * <p>Validates a value according to the field's validation rules and returns an array of errors
372      * for any failing validations. Validation rules are processed in the following order:</p>
373      * <div class="mdetail-params"><ul>
374      * 
375      * <li><b>1. Field specific validator</b>
376      * <div class="sub-desc">
377      * <p>A validator offers a way to customize and reuse a validation specification.
378      * If a field is configured with a <code>{@link #validator}</code>
379      * function, it will be passed the current field value.  The <code>{@link #validator}</code>
380      * function is expected to return either:
381      * <div class="mdetail-params"><ul>
382      * <li>Boolean <tt>true</tt> if the value is valid (validation continues).</li>
383      * <li>a String to represent the invalid message if invalid (validation halts).</li>
384      * </ul></div>
385      * </div></li>
386      * 
387      * <li><b>2. Basic Validation</b>
388      * <div class="sub-desc">
389      * <p>If the <code>{@link #validator}</code> has not halted validation,
390      * basic validation proceeds as follows:</p>
391      * 
392      * <div class="mdetail-params"><ul>
393      * 
394      * <li><code>{@link #allowBlank}</code> : (Invalid message =
395      * <code>{@link #emptyText}</code>)<div class="sub-desc">
396      * Depending on the configuration of <code>{@link #allowBlank}</code>, a
397      * blank field will cause validation to halt at this step and return
398      * Boolean true or false accordingly.  
399      * </div></li>
400      * 
401      * <li><code>{@link #minLength}</code> : (Invalid message =
402      * <code>{@link #minLengthText}</code>)<div class="sub-desc">
403      * If the passed value does not satisfy the <code>{@link #minLength}</code>
404      * specified, validation halts.
405      * </div></li>
406      * 
407      * <li><code>{@link #maxLength}</code> : (Invalid message =
408      * <code>{@link #maxLengthText}</code>)<div class="sub-desc">
409      * If the passed value does not satisfy the <code>{@link #maxLength}</code>
410      * specified, validation halts.
411      * </div></li>
412      * 
413      * </ul></div>
414      * </div></li>
415      * 
416      * <li><b>3. Preconfigured Validation Types (VTypes)</b>
417      * <div class="sub-desc">
418      * <p>If none of the prior validation steps halts validation, a field
419      * configured with a <code>{@link #vtype}</code> will utilize the
420      * corresponding {@link Ext.form.VTypes VTypes} validation function.
421      * If invalid, either the field's <code>{@link #vtypeText}</code> or
422      * the VTypes vtype Text property will be used for the invalid message.
423      * Keystrokes on the field will be filtered according to the VTypes
424      * vtype Mask property.</p>
425      * </div></li>
426      * 
427      * <li><b>4. Field specific regex test</b>
428      * <div class="sub-desc">
429      * <p>If none of the prior validation steps halts validation, a field's
430      * configured <code>{@link #regex}</code> test will be processed.
431      * The invalid message for this test is configured with
432      * <code>{@link #regexText}</code>.</p>
433      * </div></li>
434      * 
435      * @param {Mixed} value The value to validate. The processed raw value will be used if nothing is passed
436      * @return {Array} Array of any validation errors
437      */
438     getErrors: function(value) {
439         var errors = Ext.form.TextField.superclass.getErrors.apply(this, arguments);
440         
441         value = value || this.processValue(this.getRawValue());        
442         
443         if (Ext.isFunction(this.validator)) {
444             var msg = this.validator(value);
445             if (msg !== true) {
446                 errors.push(msg);
447             }
448         }
449         
450         if (value.length < 1 || value === this.emptyText) {
451             if (this.allowBlank) {
452                 //if value is blank and allowBlank is true, there cannot be any additional errors
453                 return errors;
454             } else {
455                 errors.push(this.blankText);
456             }
457         }
458         
459         if (!this.allowBlank && (value.length < 1 || value === this.emptyText)) { // if it's blank
460             errors.push(this.blankText);
461         }
462         
463         if (value.length < this.minLength) {
464             errors.push(String.format(this.minLengthText, this.minLength));
465         }
466         
467         if (value.length > this.maxLength) {
468             errors.push(String.format(this.maxLengthText, this.maxLength));
469         }
470         
471         if (this.vtype) {
472             var vt = Ext.form.VTypes;
473             if(!vt[this.vtype](value, this)){
474                 errors.push(this.vtypeText || vt[this.vtype +'Text']);
475             }
476         }
477         
478         if (this.regex && !this.regex.test(value)) {
479             errors.push(this.regexText);
480         }
481         
482         return errors;
483     },
484
485     /**
486      * Selects text in this field
487      * @param {Number} start (optional) The index where the selection should start (defaults to 0)
488      * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
489      */
490     selectText : function(start, end){
491         var v = this.getRawValue();
492         var doFocus = false;
493         if(v.length > 0){
494             start = start === undefined ? 0 : start;
495             end = end === undefined ? v.length : end;
496             var d = this.el.dom;
497             if(d.setSelectionRange){
498                 d.setSelectionRange(start, end);
499             }else if(d.createTextRange){
500                 var range = d.createTextRange();
501                 range.moveStart('character', start);
502                 range.moveEnd('character', end-v.length);
503                 range.select();
504             }
505             doFocus = Ext.isGecko || Ext.isOpera;
506         }else{
507             doFocus = true;
508         }
509         if(doFocus){
510             this.focus();
511         }
512     },
513
514     /**
515      * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
516      * This only takes effect if <tt><b>{@link #grow}</b> = true</tt>, and fires the {@link #autosize} event.
517      */
518     autoSize : function(){
519         if(!this.grow || !this.rendered){
520             return;
521         }
522         if(!this.metrics){
523             this.metrics = Ext.util.TextMetrics.createInstance(this.el);
524         }
525         var el = this.el;
526         var v = el.dom.value;
527         var d = document.createElement('div');
528         d.appendChild(document.createTextNode(v));
529         v = d.innerHTML;
530         Ext.removeNode(d);
531         d = null;
532         v += '&#160;';
533         var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
534         this.el.setWidth(w);
535         this.fireEvent('autosize', this, w);
536     },
537         
538         onDestroy: function(){
539                 if(this.validationTask){
540                         this.validationTask.cancel();
541                         this.validationTask = null;
542                 }
543                 Ext.form.TextField.superclass.onDestroy.call(this);
544         }
545 });
546 Ext.reg('textfield', Ext.form.TextField);