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 - placeholder... (defaults to null).
108      */
109     emptyText : null,
110    
111
112     // private
113     initEvents : function()
114     {
115         if (this.emptyText) {
116             this.el.attr('placeholder', this.emptyText);
117         }
118         
119         Roo.form.TextField.superclass.initEvents.call(this);
120         if(this.validationEvent == 'keyup'){
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         
128         if(this.selectOnFocus){
129             this.on("focus", this.preFocus, this);
130             
131         }
132         if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
133             this.el.on("keypress", this.filterKeys, this);
134         }
135         if(this.grow){
136             this.el.on("keyup", this.onKeyUp,  this, {buffer:50});
137             this.el.on("click", this.autoSize,  this);
138         }
139         if(this.el.is('input[type=password]') && Roo.isSafari){
140             this.el.on('keydown', this.SafariOnKeyDown, this);
141         }
142     },
143
144     processValue : function(value){
145         if(this.stripCharsRe){
146             var newValue = value.replace(this.stripCharsRe, '');
147             if(newValue !== value){
148                 this.setRawValue(newValue);
149                 return newValue;
150             }
151         }
152         return value;
153     },
154
155     filterValidation : function(e){
156         if(!e.isNavKeyPress()){
157             this.validationTask.delay(this.validationDelay);
158         }
159     },
160
161     // private
162     onKeyUp : function(e){
163         if(!e.isNavKeyPress()){
164             this.autoSize();
165         }
166     },
167
168     /**
169      * Resets the current field value to the originally-loaded value and clears any validation messages.
170      *  
171      */
172     reset : function(){
173         Roo.form.TextField.superclass.reset.call(this);
174        
175     },
176
177     
178     // private
179     preFocus : function(){
180         
181         if(this.selectOnFocus){
182             this.el.dom.select();
183         }
184     },
185
186     
187     // private
188     filterKeys : function(e){
189         var k = e.getKey();
190         if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
191             return;
192         }
193         var c = e.getCharCode(), cc = String.fromCharCode(c);
194         if(Roo.isIE && (e.isSpecialKey() || !cc)){
195             return;
196         }
197         if(!this.maskRe.test(cc)){
198             e.stopEvent();
199         }
200     },
201
202     setValue : function(v){
203         
204         Roo.form.TextField.superclass.setValue.apply(this, arguments);
205         
206         this.autoSize();
207     },
208
209     /**
210      * Validates a value according to the field's validation rules and marks the field as invalid
211      * if the validation fails
212      * @param {Mixed} value The value to validate
213      * @return {Boolean} True if the value is valid, else false
214      */
215     validateValue : function(value){
216         if(value.length < 1)  { // if it's blank
217              if(this.allowBlank){
218                 this.clearInvalid();
219                 return true;
220              }else{
221                 this.markInvalid(this.blankText);
222                 return false;
223              }
224         }
225         if(value.length < this.minLength){
226             this.markInvalid(String.format(this.minLengthText, this.minLength));
227             return false;
228         }
229         if(value.length > this.maxLength){
230             this.markInvalid(String.format(this.maxLengthText, this.maxLength));
231             return false;
232         }
233         if(this.vtype){
234             var vt = Roo.form.VTypes;
235             if(!vt[this.vtype](value, this)){
236                 this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
237                 return false;
238             }
239         }
240         if(typeof this.validator == "function"){
241             var msg = this.validator(value);
242             if(msg !== true){
243                 this.markInvalid(msg);
244                 return false;
245             }
246         }
247         if(this.regex && !this.regex.test(value)){
248             this.markInvalid(this.regexText);
249             return false;
250         }
251         return true;
252     },
253
254     /**
255      * Selects text in this field
256      * @param {Number} start (optional) The index where the selection should start (defaults to 0)
257      * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
258      */
259     selectText : function(start, end){
260         var v = this.getRawValue();
261         if(v.length > 0){
262             start = start === undefined ? 0 : start;
263             end = end === undefined ? v.length : end;
264             var d = this.el.dom;
265             if(d.setSelectionRange){
266                 d.setSelectionRange(start, end);
267             }else if(d.createTextRange){
268                 var range = d.createTextRange();
269                 range.moveStart("character", start);
270                 range.moveEnd("character", v.length-end);
271                 range.select();
272             }
273         }
274     },
275
276     /**
277      * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
278      * This only takes effect if grow = true, and fires the autosize event.
279      */
280     autoSize : function(){
281         if(!this.grow || !this.rendered){
282             return;
283         }
284         if(!this.metrics){
285             this.metrics = Roo.util.TextMetrics.createInstance(this.el);
286         }
287         var el = this.el;
288         var v = el.dom.value;
289         var d = document.createElement('div');
290         d.appendChild(document.createTextNode(v));
291         v = d.innerHTML;
292         d = null;
293         v += "&#160;";
294         var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
295         this.el.setWidth(w);
296         this.fireEvent("autosize", this, w);
297     },
298     
299     // private
300     SafariOnKeyDown : function(event)
301     {
302         // this is a workaround for a password hang bug on chrome/ webkit.
303         
304         var isSelectAll = false;
305         
306         if(this.el.dom.selectionEnd > 0){
307             isSelectAll = (this.el.dom.selectionEnd - this.el.dom.selectionStart - this.getValue().length == 0) ? true : false;
308         }
309         if(((event.getKey() == 8 || event.getKey() == 46) && this.getValue().length ==1)){ // backspace and delete key
310             event.preventDefault();
311             this.setValue('');
312             return;
313         }
314         
315         if(isSelectAll){ // backspace and delete key
316             
317             event.preventDefault();
318             // this is very hacky as keydown always get's upper case.
319             //
320             var cc = String.fromCharCode(event.getCharCode());
321             this.setValue( event.shiftKey ?  cc : cc.toLowerCase());
322             
323         }
324         
325         
326     }
327 });