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