Roo/form/TextField.js
[roojs1] / Roo / form / TextField.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11  
12
13 /**
14  * @class Roo.form.TextField
15  * @extends Roo.form.Field
16  * Basic text field.  Can be used as a direct replacement for traditional text inputs, or as the base
17  * class for more sophisticated input controls (like {@link Roo.form.TextArea} and {@link Roo.form.ComboBox}).
18  * @constructor
19  * Creates a new TextField
20  * @param {Object} config Configuration options
21  */
22 Roo.form.TextField = function(config){
23     Roo.form.TextField.superclass.constructor.call(this, config);
24     this.addEvents({
25         /**
26          * @event autosize
27          * Fires when the autosize function is triggered.  The field may or may not have actually changed size
28          * according to the default logic, but this event provides a hook for the developer to apply additional
29          * logic at runtime to resize the field if needed.
30              * @param {Roo.form.Field} this This text field
31              * @param {Number} width The new field width
32              */
33         autosize : true
34     });
35 };
36
37 Roo.extend(Roo.form.TextField, Roo.form.Field,  {
38     /**
39      * @cfg {Boolean} grow True if this field should automatically grow and shrink to its content
40      */
41     grow : false,
42     /**
43      * @cfg {Number} growMin The minimum width to allow when grow = true (defaults to 30)
44      */
45     growMin : 30,
46     /**
47      * @cfg {Number} growMax The maximum width to allow when grow = true (defaults to 800)
48      */
49     growMax : 800,
50     /**
51      * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
52      */
53     vtype : null,
54     /**
55      * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
56      */
57     maskRe : null,
58     /**
59      * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
60      */
61     disableKeyFilter : false,
62     /**
63      * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
64      */
65     allowBlank : true,
66     /**
67      * @cfg {Number} minLength Minimum input field length required (defaults to 0)
68      */
69     minLength : 0,
70     /**
71      * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
72      */
73     maxLength : Number.MAX_VALUE,
74     /**
75      * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
76      */
77     minLengthText : "The minimum length for this field is {0}",
78     /**
79      * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
80      */
81     maxLengthText : "The maximum length for this field is {0}",
82     /**
83      * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
84      */
85     selectOnFocus : false,
86     /**
87      * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
88      */
89     blankText : "This field is required",
90     /**
91      * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
92      * If available, this function will be called only after the basic validators all return true, and will be passed the
93      * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
94      */
95     validator : null,
96     /**
97      * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
98      * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
99      * current field value.  If the test fails, the field will be marked invalid using {@link #regexText}.
100      */
101     regex : null,
102     /**
103      * @cfg {String} regexText The error text to display if {@link #regex} is used and the test fails during validation (defaults to "")
104      */
105     regexText : "",
106     /**
107      * @cfg {String} emptyText The default text to display in an empty field (defaults to null).
108      */
109     emptyText : null,
110     /**
111      * @cfg {String} emptyClass The CSS class to apply to an empty field to style the {@link #emptyText} (defaults to
112      * 'x-form-empty-field').  This class is automatically added and removed as needed depending on the current field value.
113      */
114     emptyClass : 'x-form-empty-field',
115
116     // private
117     initEvents : function(){
118         Roo.form.TextField.superclass.initEvents.call(this);
119         if(this.validationEvent == 'keyup'){
120             Roo.log('in??');
121             this.validationTask = new Roo.util.DelayedTask(this.validate, this);
122             this.el.on('keyup', this.filterValidation, this);
123         }
124         else if(this.validationEvent !== false){
125             this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
126         }
127         if(this.selectOnFocus || this.emptyText){
128             this.on("focus", this.preFocus, this);
129             if(this.emptyText){
130                 this.on('blur', this.postBlur, this);
131                 this.applyEmptyText();
132             }
133         }
134         if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
135             this.el.on("keypress", this.filterKeys, this);
136         }
137         if(this.grow){
138             this.el.on("keyup", this.onKeyUp,  this, {buffer:50});
139             this.el.on("click", this.autoSize,  this);
140         }
141     },
142
143     processValue : function(value){
144         if(this.stripCharsRe){
145             var newValue = value.replace(this.stripCharsRe, '');
146             if(newValue !== value){
147                 this.setRawValue(newValue);
148                 return newValue;
149             }
150         }
151         return value;
152     },
153
154     filterValidation : function(e){
155         if(!e.isNavKeyPress()){
156             this.validationTask.delay(this.validationDelay);
157         }
158     },
159
160     // private
161     onKeyUp : function(e){
162         if(!e.isNavKeyPress()){
163             this.autoSize();
164         }
165     },
166
167     /**
168      * Resets the current field value to the originally-loaded value and clears any validation messages.
169      * Also adds emptyText and emptyClass if the original value was blank.
170      */
171     reset : function(){
172         Roo.form.TextField.superclass.reset.call(this);
173         this.applyEmptyText();
174     },
175
176     applyEmptyText : function(){
177         if(this.rendered && this.emptyText && this.getRawValue().length < 1){
178             this.setRawValue(this.emptyText);
179             this.el.addClass(this.emptyClass);
180         }
181     },
182
183     // private
184     preFocus : function(){
185         if(this.emptyText){
186             if(this.el.dom.value == this.emptyText){
187                 this.setRawValue('');
188             }
189             this.el.removeClass(this.emptyClass);
190         }
191         if(this.selectOnFocus){
192             this.el.dom.select();
193         }
194     },
195
196     // private
197     postBlur : function(){
198         this.applyEmptyText();
199     },
200
201     // private
202     filterKeys : function(e){
203         var k = e.getKey();
204         if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
205             return;
206         }
207         var c = e.getCharCode(), cc = String.fromCharCode(c);
208         if(Roo.isIE && (e.isSpecialKey() || !cc)){
209             return;
210         }
211         if(!this.maskRe.test(cc)){
212             e.stopEvent();
213         }
214     },
215
216     setValue : function(v){
217         if(this.emptyText && this.el && v !== undefined && v !== null && v !== ''){
218             this.el.removeClass(this.emptyClass);
219         }
220         Roo.form.TextField.superclass.setValue.apply(this, arguments);
221         this.applyEmptyText();
222         this.autoSize();
223     },
224
225     /**
226      * Validates a value according to the field's validation rules and marks the field as invalid
227      * if the validation fails
228      * @param {Mixed} value The value to validate
229      * @return {Boolean} True if the value is valid, else false
230      */
231     validateValue : function(value){
232         if(value.length < 1 || value === this.emptyText){ // if it's blank
233              if(this.allowBlank){
234                 this.clearInvalid();
235                 return true;
236              }else{
237                 this.markInvalid(this.blankText);
238                 return false;
239              }
240         }
241         if(value.length < this.minLength){
242             this.markInvalid(String.format(this.minLengthText, this.minLength));
243             return false;
244         }
245         if(value.length > this.maxLength){
246             this.markInvalid(String.format(this.maxLengthText, this.maxLength));
247             return false;
248         }
249         if(this.vtype){
250             var vt = Roo.form.VTypes;
251             if(!vt[this.vtype](value, this)){
252                 this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
253                 return false;
254             }
255         }
256         if(typeof this.validator == "function"){
257             var msg = this.validator(value);
258             if(msg !== true){
259                 this.markInvalid(msg);
260                 return false;
261             }
262         }
263         if(this.regex && !this.regex.test(value)){
264             this.markInvalid(this.regexText);
265             return false;
266         }
267         return true;
268     },
269
270     /**
271      * Selects text in this field
272      * @param {Number} start (optional) The index where the selection should start (defaults to 0)
273      * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
274      */
275     selectText : function(start, end){
276         var v = this.getRawValue();
277         if(v.length > 0){
278             start = start === undefined ? 0 : start;
279             end = end === undefined ? v.length : end;
280             var d = this.el.dom;
281             if(d.setSelectionRange){
282                 d.setSelectionRange(start, end);
283             }else if(d.createTextRange){
284                 var range = d.createTextRange();
285                 range.moveStart("character", start);
286                 range.moveEnd("character", v.length-end);
287                 range.select();
288             }
289         }
290     },
291
292     /**
293      * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
294      * This only takes effect if grow = true, and fires the autosize event.
295      */
296     autoSize : function(){
297         if(!this.grow || !this.rendered){
298             return;
299         }
300         if(!this.metrics){
301             this.metrics = Roo.util.TextMetrics.createInstance(this.el);
302         }
303         var el = this.el;
304         var v = el.dom.value;
305         var d = document.createElement('div');
306         d.appendChild(document.createTextNode(v));
307         v = d.innerHTML;
308         d = null;
309         v += "&#160;";
310         var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
311         this.el.setWidth(w);
312         this.fireEvent("autosize", this, w);
313     }
314 });