Upgrade to ExtJS 3.2.1 - Released 04/27/2010
[extjs.git] / src / widgets / form / DateField.js
1 /*!
2  * Ext JS Library 3.2.1
3  * Copyright(c) 2006-2010 Ext JS, Inc.
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.form.DateField
9  * @extends Ext.form.TriggerField
10  * Provides a date input field with a {@link Ext.DatePicker} dropdown and automatic date validation.
11  * @constructor
12  * Create a new DateField
13  * @param {Object} config
14  * @xtype datefield
15  */
16 Ext.form.DateField = Ext.extend(Ext.form.TriggerField,  {
17     /**
18      * @cfg {String} format
19      * The default date format string which can be overriden for localization support.  The format must be
20      * valid according to {@link Date#parseDate} (defaults to <tt>'m/d/Y'</tt>).
21      */
22     format : "m/d/Y",
23     /**
24      * @cfg {String} altFormats
25      * Multiple date formats separated by "<tt>|</tt>" to try when parsing a user input value and it
26      * does not match the defined format (defaults to
27      * <tt>'m/d/Y|n/j/Y|n/j/y|m/j/y|n/d/y|m/j/Y|n/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d'</tt>).
28      */
29     altFormats : "m/d/Y|n/j/Y|n/j/y|m/j/y|n/d/y|m/j/Y|n/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d",
30     /**
31      * @cfg {String} disabledDaysText
32      * The tooltip to display when the date falls on a disabled day (defaults to <tt>'Disabled'</tt>)
33      */
34     disabledDaysText : "Disabled",
35     /**
36      * @cfg {String} disabledDatesText
37      * The tooltip text to display when the date falls on a disabled date (defaults to <tt>'Disabled'</tt>)
38      */
39     disabledDatesText : "Disabled",
40     /**
41      * @cfg {String} minText
42      * The error text to display when the date in the cell is before <tt>{@link #minValue}</tt> (defaults to
43      * <tt>'The date in this field must be after {minValue}'</tt>).
44      */
45     minText : "The date in this field must be equal to or after {0}",
46     /**
47      * @cfg {String} maxText
48      * The error text to display when the date in the cell is after <tt>{@link #maxValue}</tt> (defaults to
49      * <tt>'The date in this field must be before {maxValue}'</tt>).
50      */
51     maxText : "The date in this field must be equal to or before {0}",
52     /**
53      * @cfg {String} invalidText
54      * The error text to display when the date in the field is invalid (defaults to
55      * <tt>'{value} is not a valid date - it must be in the format {format}'</tt>).
56      */
57     invalidText : "{0} is not a valid date - it must be in the format {1}",
58     /**
59      * @cfg {String} triggerClass
60      * An additional CSS class used to style the trigger button.  The trigger will always get the
61      * class <tt>'x-form-trigger'</tt> and <tt>triggerClass</tt> will be <b>appended</b> if specified
62      * (defaults to <tt>'x-form-date-trigger'</tt> which displays a calendar icon).
63      */
64     triggerClass : 'x-form-date-trigger',
65     /**
66      * @cfg {Boolean} showToday
67      * <tt>false</tt> to hide the footer area of the DatePicker containing the Today button and disable
68      * the keyboard handler for spacebar that selects the current date (defaults to <tt>true</tt>).
69      */
70     showToday : true,
71     /**
72      * @cfg {Date/String} minValue
73      * The minimum allowed date. Can be either a Javascript date object or a string date in a
74      * valid format (defaults to null).
75      */
76     /**
77      * @cfg {Date/String} maxValue
78      * The maximum allowed date. Can be either a Javascript date object or a string date in a
79      * valid format (defaults to null).
80      */
81     /**
82      * @cfg {Array} disabledDays
83      * An array of days to disable, 0 based (defaults to null). Some examples:<pre><code>
84 // disable Sunday and Saturday:
85 disabledDays:  [0, 6]
86 // disable weekdays:
87 disabledDays: [1,2,3,4,5]
88      * </code></pre>
89      */
90     /**
91      * @cfg {Array} disabledDates
92      * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
93      * expression so they are very powerful. Some examples:<pre><code>
94 // disable these exact dates:
95 disabledDates: ["03/08/2003", "09/16/2003"]
96 // disable these days for every year:
97 disabledDates: ["03/08", "09/16"]
98 // only match the beginning (useful if you are using short years):
99 disabledDates: ["^03/08"]
100 // disable every day in March 2006:
101 disabledDates: ["03/../2006"]
102 // disable every day in every March:
103 disabledDates: ["^03"]
104      * </code></pre>
105      * Note that the format of the dates included in the array should exactly match the {@link #format} config.
106      * In order to support regular expressions, if you are using a {@link #format date format} that has "." in
107      * it, you will have to escape the dot when restricting dates. For example: <tt>["03\\.08\\.03"]</tt>.
108      */
109     /**
110      * @cfg {String/Object} autoCreate
111      * A {@link Ext.DomHelper DomHelper element specification object}, or <tt>true</tt> for the default element
112      * specification object:<pre><code>
113      * autoCreate: {tag: "input", type: "text", size: "10", autocomplete: "off"}
114      * </code></pre>
115      */
116
117     // private
118     defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
119
120     // in the absence of a time value, a default value of 12 noon will be used
121     // (note: 12 noon was chosen because it steers well clear of all DST timezone changes)
122     initTime: '12', // 24 hour format
123
124     initTimeFormat: 'H',
125
126     // PUBLIC -- to be documented
127     safeParse : function(value, format) {
128         if (/[gGhH]/.test(format.replace(/(\\.)/g, ''))) {
129             // if parse format contains hour information, no DST adjustment is necessary
130             return Date.parseDate(value, format);
131         } else {
132             // set time to 12 noon, then clear the time
133             var parsedDate = Date.parseDate(value + ' ' + this.initTime, format + ' ' + this.initTimeFormat);
134             
135             if (parsedDate) return parsedDate.clearTime();
136         }
137     },
138
139     initComponent : function(){
140         Ext.form.DateField.superclass.initComponent.call(this);
141
142         this.addEvents(
143             /**
144              * @event select
145              * Fires when a date is selected via the date picker.
146              * @param {Ext.form.DateField} this
147              * @param {Date} date The date that was selected
148              */
149             'select'
150         );
151
152         if(Ext.isString(this.minValue)){
153             this.minValue = this.parseDate(this.minValue);
154         }
155         if(Ext.isString(this.maxValue)){
156             this.maxValue = this.parseDate(this.maxValue);
157         }
158         this.disabledDatesRE = null;
159         this.initDisabledDays();
160     },
161
162     initEvents: function() {
163         Ext.form.DateField.superclass.initEvents.call(this);
164         this.keyNav = new Ext.KeyNav(this.el, {
165             "down": function(e) {
166                 this.onTriggerClick();
167             },
168             scope: this,
169             forceKeyDown: true
170         });
171     },
172
173
174     // private
175     initDisabledDays : function(){
176         if(this.disabledDates){
177             var dd = this.disabledDates,
178                 len = dd.length - 1,
179                 re = "(?:";
180
181             Ext.each(dd, function(d, i){
182                 re += Ext.isDate(d) ? '^' + Ext.escapeRe(d.dateFormat(this.format)) + '$' : dd[i];
183                 if(i != len){
184                     re += '|';
185                 }
186             }, this);
187             this.disabledDatesRE = new RegExp(re + ')');
188         }
189     },
190
191     /**
192      * Replaces any existing disabled dates with new values and refreshes the DatePicker.
193      * @param {Array} disabledDates An array of date strings (see the <tt>{@link #disabledDates}</tt> config
194      * for details on supported values) used to disable a pattern of dates.
195      */
196     setDisabledDates : function(dd){
197         this.disabledDates = dd;
198         this.initDisabledDays();
199         if(this.menu){
200             this.menu.picker.setDisabledDates(this.disabledDatesRE);
201         }
202     },
203
204     /**
205      * Replaces any existing disabled days (by index, 0-6) with new values and refreshes the DatePicker.
206      * @param {Array} disabledDays An array of disabled day indexes. See the <tt>{@link #disabledDays}</tt>
207      * config for details on supported values.
208      */
209     setDisabledDays : function(dd){
210         this.disabledDays = dd;
211         if(this.menu){
212             this.menu.picker.setDisabledDays(dd);
213         }
214     },
215
216     /**
217      * Replaces any existing <tt>{@link #minValue}</tt> with the new value and refreshes the DatePicker.
218      * @param {Date} value The minimum date that can be selected
219      */
220     setMinValue : function(dt){
221         this.minValue = (Ext.isString(dt) ? this.parseDate(dt) : dt);
222         if(this.menu){
223             this.menu.picker.setMinDate(this.minValue);
224         }
225     },
226
227     /**
228      * Replaces any existing <tt>{@link #maxValue}</tt> with the new value and refreshes the DatePicker.
229      * @param {Date} value The maximum date that can be selected
230      */
231     setMaxValue : function(dt){
232         this.maxValue = (Ext.isString(dt) ? this.parseDate(dt) : dt);
233         if(this.menu){
234             this.menu.picker.setMaxDate(this.maxValue);
235         }
236     },
237     
238     /**
239      * Runs all of NumberFields validations and returns an array of any errors. Note that this first
240      * runs TextField's validations, so the returned array is an amalgamation of all field errors.
241      * The additional validation checks are testing that the date format is valid, that the chosen
242      * date is within the min and max date constraints set, that the date chosen is not in the disabledDates
243      * regex and that the day chosed is not one of the disabledDays.
244      * @param {Mixed} value The value to get errors for (defaults to the current field value)
245      * @return {Array} All validation errors for this field
246      */
247     getErrors: function(value) {
248         var errors = Ext.form.DateField.superclass.getErrors.apply(this, arguments);
249         
250         value = this.formatDate(value || this.processValue(this.getRawValue()));
251         
252         if (value.length < 1) { // if it's blank and textfield didn't flag it then it's valid
253              return errors;
254         }
255         
256         var svalue = value;
257         value = this.parseDate(value);
258         if (!value) {
259             errors.push(String.format(this.invalidText, svalue, this.format));
260             return errors;
261         }
262         
263         var time = value.getTime();
264         if (this.minValue && time < this.minValue.getTime()) {
265             errors.push(String.format(this.minText, this.formatDate(this.minValue)));
266         }
267         
268         if (this.maxValue && time > this.maxValue.getTime()) {
269             errors.push(String.format(this.maxText, this.formatDate(this.maxValue)));
270         }
271         
272         if (this.disabledDays) {
273             var day = value.getDay();
274             
275             for(var i = 0; i < this.disabledDays.length; i++) {
276                 if (day === this.disabledDays[i]) {
277                     errors.push(this.disabledDaysText);
278                     break;
279                 }
280             }
281         }
282         
283         var fvalue = this.formatDate(value);
284         if (this.disabledDatesRE && this.disabledDatesRE.test(fvalue)) {
285             errors.push(String.format(this.disabledDatesText, fvalue));
286         }
287         
288         return errors;
289     },
290
291     // private
292     // Provides logic to override the default TriggerField.validateBlur which just returns true
293     validateBlur : function(){
294         return !this.menu || !this.menu.isVisible();
295     },
296
297     /**
298      * Returns the current date value of the date field.
299      * @return {Date} The date value
300      */
301     getValue : function(){
302         return this.parseDate(Ext.form.DateField.superclass.getValue.call(this)) || "";
303     },
304
305     /**
306      * Sets the value of the date field.  You can pass a date object or any string that can be
307      * parsed into a valid date, using <tt>{@link #format}</tt> as the date format, according
308      * to the same rules as {@link Date#parseDate} (the default format used is <tt>"m/d/Y"</tt>).
309      * <br />Usage:
310      * <pre><code>
311 //All of these calls set the same date value (May 4, 2006)
312
313 //Pass a date object:
314 var dt = new Date('5/4/2006');
315 dateField.setValue(dt);
316
317 //Pass a date string (default format):
318 dateField.setValue('05/04/2006');
319
320 //Pass a date string (custom format):
321 dateField.format = 'Y-m-d';
322 dateField.setValue('2006-05-04');
323 </code></pre>
324      * @param {String/Date} date The date or valid date string
325      * @return {Ext.form.Field} this
326      */
327     setValue : function(date){
328         return Ext.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
329     },
330
331     // private
332     parseDate : function(value) {
333         if(!value || Ext.isDate(value)){
334             return value;
335         }
336
337         var v = this.safeParse(value, this.format),
338             af = this.altFormats,
339             afa = this.altFormatsArray;
340
341         if (!v && af) {
342             afa = afa || af.split("|");
343
344             for (var i = 0, len = afa.length; i < len && !v; i++) {
345                 v = this.safeParse(value, afa[i]);
346             }
347         }
348         return v;
349     },
350
351     // private
352     onDestroy : function(){
353         Ext.destroy(this.menu, this.keyNav);
354         Ext.form.DateField.superclass.onDestroy.call(this);
355     },
356
357     // private
358     formatDate : function(date){
359         return Ext.isDate(date) ? date.dateFormat(this.format) : date;
360     },
361
362     /**
363      * @method onTriggerClick
364      * @hide
365      */
366     // private
367     // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
368     onTriggerClick : function(){
369         if(this.disabled){
370             return;
371         }
372         if(this.menu == null){
373             this.menu = new Ext.menu.DateMenu({
374                 hideOnClick: false,
375                 focusOnSelect: false
376             });
377         }
378         this.onFocus();
379         Ext.apply(this.menu.picker,  {
380             minDate : this.minValue,
381             maxDate : this.maxValue,
382             disabledDatesRE : this.disabledDatesRE,
383             disabledDatesText : this.disabledDatesText,
384             disabledDays : this.disabledDays,
385             disabledDaysText : this.disabledDaysText,
386             format : this.format,
387             showToday : this.showToday,
388             minText : String.format(this.minText, this.formatDate(this.minValue)),
389             maxText : String.format(this.maxText, this.formatDate(this.maxValue))
390         });
391         this.menu.picker.setValue(this.getValue() || new Date());
392         this.menu.show(this.el, "tl-bl?");
393         this.menuEvents('on');
394     },
395
396     //private
397     menuEvents: function(method){
398         this.menu[method]('select', this.onSelect, this);
399         this.menu[method]('hide', this.onMenuHide, this);
400         this.menu[method]('show', this.onFocus, this);
401     },
402
403     onSelect: function(m, d){
404         this.setValue(d);
405         this.fireEvent('select', this, d);
406         this.menu.hide();
407     },
408
409     onMenuHide: function(){
410         this.focus(false, 60);
411         this.menuEvents('un');
412     },
413
414     // private
415     beforeBlur : function(){
416         var v = this.parseDate(this.getRawValue());
417         if(v){
418             this.setValue(v);
419         }
420     }
421
422     /**
423      * @cfg {Boolean} grow @hide
424      */
425     /**
426      * @cfg {Number} growMin @hide
427      */
428     /**
429      * @cfg {Number} growMax @hide
430      */
431     /**
432      * @hide
433      * @method autoSize
434      */
435 });
436 Ext.reg('datefield', Ext.form.DateField);