Upgrade to ExtJS 4.0.2 - Released 06/09/2011
[extjs.git] / docs / source / Date2.html
1 <!DOCTYPE html>
2 <html>
3 <head>
4   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5   <title>The source code</title>
6   <link href="../prettify/prettify.css" type="text/css" rel="stylesheet" />
7   <script type="text/javascript" src="../prettify/prettify.js"></script>
8   <style type="text/css">
9     .highlight { display: block; background-color: #ddd; }
10   </style>
11   <script type="text/javascript">
12     function highlight() {
13       document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
14     }
15   </script>
16 </head>
17 <body onload="prettyPrint(); highlight();">
18   <pre class="prettyprint lang-js"><span id='Ext-form-field-Date'>/**
19 </span> * @class Ext.form.field.Date
20  * @extends Ext.form.field.Picker
21
22 Provides a date input field with a {@link Ext.picker.Date date picker} dropdown and automatic date
23 validation.
24
25 This field recognizes and uses the JavaScript Date object as its main {@link #value} type. In addition,
26 it recognizes string values which are parsed according to the {@link #format} and/or {@link #altFormats}
27 configs. These may be reconfigured to use date formats appropriate for the user's locale.
28
29 The field may be limited to a certain range of dates by using the {@link #minValue}, {@link #maxValue},
30 {@link #disabledDays}, and {@link #disabledDates} config parameters. These configurations will be used both
31 in the field's validation, and in the date picker dropdown by preventing invalid dates from being selected.
32 {@img Ext.form.Date/Ext.form.Date.png Ext.form.Date component}
33 #Example usage:#
34
35     Ext.create('Ext.form.Panel', {
36         width: 300,
37         bodyPadding: 10,
38         title: 'Dates',
39         items: [{
40             xtype: 'datefield',
41             anchor: '100%',
42             fieldLabel: 'From',
43             name: 'from_date',
44             maxValue: new Date()  // limited to the current date or prior
45         }, {
46             xtype: 'datefield',
47             anchor: '100%',
48             fieldLabel: 'To',
49             name: 'to_date',
50             value: new Date()  // defaults to today
51         }],
52             renderTo: Ext.getBody()
53     });
54
55 #Date Formats Examples#
56
57 This example shows a couple of different date format parsing scenarios. Both use custom date format
58 configurations; the first one matches the configured `format` while the second matches the `altFormats`.
59
60     Ext.create('Ext.form.Panel', {
61         renderTo: Ext.getBody(),
62         width: 300,
63         bodyPadding: 10,
64         title: 'Dates',
65         items: [{
66             xtype: 'datefield',
67             anchor: '100%',
68             fieldLabel: 'Date',
69             name: 'date',
70             // The value matches the format; will be parsed and displayed using that format.
71             format: 'm d Y',
72             value: '2 4 1978'
73         }, {
74             xtype: 'datefield',
75             anchor: '100%',
76             fieldLabel: 'Date',
77             name: 'date',
78             // The value does not match the format, but does match an altFormat; will be parsed
79             // using the altFormat and displayed using the format.
80             format: 'm d Y',
81             altFormats: 'm,d,Y|m.d.Y',
82             value: '2.4.1978'
83         }]
84     });
85
86  * 
87  * @markdown
88  * @docauthor Jason Johnston &lt;jason@sencha.com&gt;
89  */
90 Ext.define('Ext.form.field.Date', {
91     extend:'Ext.form.field.Picker',
92     alias: 'widget.datefield',
93     requires: ['Ext.picker.Date'],
94     alternateClassName: ['Ext.form.DateField', 'Ext.form.Date'],
95
96 <span id='Ext-form-field-Date-cfg-format'>    /**
97 </span>     * @cfg {String} format
98      * The default date format string which can be overriden for localization support.  The format must be
99      * valid according to {@link Ext.Date#parse} (defaults to &lt;tt&gt;'m/d/Y'&lt;/tt&gt;).
100      */
101     format : &quot;m/d/Y&quot;,
102 <span id='Ext-form-field-Date-cfg-altFormats'>    /**
103 </span>     * @cfg {String} altFormats
104      * Multiple date formats separated by &quot;&lt;tt&gt;|&lt;/tt&gt;&quot; to try when parsing a user input value and it
105      * does not match the defined format (defaults to
106      * &lt;tt&gt;'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|n-j|n/j'&lt;/tt&gt;).
107      */
108     altFormats : &quot;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|n-j|n/j&quot;,
109 <span id='Ext-form-field-Date-cfg-disabledDaysText'>    /**
110 </span>     * @cfg {String} disabledDaysText
111      * The tooltip to display when the date falls on a disabled day (defaults to &lt;tt&gt;'Disabled'&lt;/tt&gt;)
112      */
113     disabledDaysText : &quot;Disabled&quot;,
114 <span id='Ext-form-field-Date-cfg-disabledDatesText'>    /**
115 </span>     * @cfg {String} disabledDatesText
116      * The tooltip text to display when the date falls on a disabled date (defaults to &lt;tt&gt;'Disabled'&lt;/tt&gt;)
117      */
118     disabledDatesText : &quot;Disabled&quot;,
119 <span id='Ext-form-field-Date-cfg-minText'>    /**
120 </span>     * @cfg {String} minText
121      * The error text to display when the date in the cell is before &lt;tt&gt;{@link #minValue}&lt;/tt&gt; (defaults to
122      * &lt;tt&gt;'The date in this field must be after {minValue}'&lt;/tt&gt;).
123      */
124     minText : &quot;The date in this field must be equal to or after {0}&quot;,
125 <span id='Ext-form-field-Date-cfg-maxText'>    /**
126 </span>     * @cfg {String} maxText
127      * The error text to display when the date in the cell is after &lt;tt&gt;{@link #maxValue}&lt;/tt&gt; (defaults to
128      * &lt;tt&gt;'The date in this field must be before {maxValue}'&lt;/tt&gt;).
129      */
130     maxText : &quot;The date in this field must be equal to or before {0}&quot;,
131 <span id='Ext-form-field-Date-cfg-invalidText'>    /**
132 </span>     * @cfg {String} invalidText
133      * The error text to display when the date in the field is invalid (defaults to
134      * &lt;tt&gt;'{value} is not a valid date - it must be in the format {format}'&lt;/tt&gt;).
135      */
136     invalidText : &quot;{0} is not a valid date - it must be in the format {1}&quot;,
137 <span id='Ext-form-field-Date-cfg-triggerCls'>    /**
138 </span>     * @cfg {String} triggerCls
139      * An additional CSS class used to style the trigger button.  The trigger will always get the
140      * class &lt;tt&gt;'x-form-trigger'&lt;/tt&gt; and &lt;tt&gt;triggerCls&lt;/tt&gt; will be &lt;b&gt;appended&lt;/b&gt; if specified
141      * (defaults to &lt;tt&gt;'x-form-date-trigger'&lt;/tt&gt; which displays a calendar icon).
142      */
143     triggerCls : Ext.baseCSSPrefix + 'form-date-trigger',
144 <span id='Ext-form-field-Date-cfg-showToday'>    /**
145 </span>     * @cfg {Boolean} showToday
146      * &lt;tt&gt;false&lt;/tt&gt; to hide the footer area of the Date picker containing the Today button and disable
147      * the keyboard handler for spacebar that selects the current date (defaults to &lt;tt&gt;true&lt;/tt&gt;).
148      */
149     showToday : true,
150 <span id='Ext-form-field-Date-cfg-minValue'>    /**
151 </span>     * @cfg {Date/String} minValue
152      * The minimum allowed date. Can be either a Javascript date object or a string date in a
153      * valid format (defaults to undefined).
154      */
155 <span id='Ext-form-field-Date-cfg-maxValue'>    /**
156 </span>     * @cfg {Date/String} maxValue
157      * The maximum allowed date. Can be either a Javascript date object or a string date in a
158      * valid format (defaults to undefined).
159      */
160 <span id='Ext-form-field-Date-cfg-disabledDays'>    /**
161 </span>     * @cfg {Array} disabledDays
162      * An array of days to disable, 0 based (defaults to undefined). Some examples:&lt;pre&gt;&lt;code&gt;
163 // disable Sunday and Saturday:
164 disabledDays:  [0, 6]
165 // disable weekdays:
166 disabledDays: [1,2,3,4,5]
167      * &lt;/code&gt;&lt;/pre&gt;
168      */
169 <span id='Ext-form-field-Date-cfg-disabledDates'>    /**
170 </span>     * @cfg {Array} disabledDates
171      * An array of &quot;dates&quot; to disable, as strings. These strings will be used to build a dynamic regular
172      * expression so they are very powerful. Some examples:&lt;pre&gt;&lt;code&gt;
173 // disable these exact dates:
174 disabledDates: [&quot;03/08/2003&quot;, &quot;09/16/2003&quot;]
175 // disable these days for every year:
176 disabledDates: [&quot;03/08&quot;, &quot;09/16&quot;]
177 // only match the beginning (useful if you are using short years):
178 disabledDates: [&quot;^03/08&quot;]
179 // disable every day in March 2006:
180 disabledDates: [&quot;03/../2006&quot;]
181 // disable every day in every March:
182 disabledDates: [&quot;^03&quot;]
183      * &lt;/code&gt;&lt;/pre&gt;
184      * Note that the format of the dates included in the array should exactly match the {@link #format} config.
185      * In order to support regular expressions, if you are using a {@link #format date format} that has &quot;.&quot; in
186      * it, you will have to escape the dot when restricting dates. For example: &lt;tt&gt;[&quot;03\\.08\\.03&quot;]&lt;/tt&gt;.
187      */
188     
189 <span id='Ext-form-field-Date-cfg-submitFormat'>    /**
190 </span>     * @cfg {String} submitFormat The date format string which will be submitted to the server.  
191      * The format must be valid according to {@link Ext.Date#parse} (defaults to &lt;tt&gt;{@link #format}&lt;/tt&gt;).
192      */
193
194     // in the absence of a time value, a default value of 12 noon will be used
195     // (note: 12 noon was chosen because it steers well clear of all DST timezone changes)
196     initTime: '12', // 24 hour format
197
198     initTimeFormat: 'H',
199
200     matchFieldWidth: false,
201 <span id='Ext-form-field-Date-cfg-startDay'>    /**
202 </span>     * @cfg {Number} startDay
203      * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
204      */
205     startDay: 0,
206     
207     initComponent : function(){
208         var me = this,
209             isString = Ext.isString,
210             min, max;
211
212         min = me.minValue;
213         max = me.maxValue;
214         if(isString(min)){
215             me.minValue = me.parseDate(min);
216         }
217         if(isString(max)){
218             me.maxValue = me.parseDate(max);
219         }
220         me.disabledDatesRE = null;
221         me.initDisabledDays();
222
223         me.callParent();
224     },
225
226     initValue: function() {
227         var me = this,
228             value = me.value;
229
230         // If a String value was supplied, try to convert it to a proper Date
231         if (Ext.isString(value)) {
232             me.value = me.rawToValue(value);
233         }
234
235         me.callParent();
236     },
237
238     // private
239     initDisabledDays : function(){
240         if(this.disabledDates){
241             var dd = this.disabledDates,
242                 len = dd.length - 1,
243                 re = &quot;(?:&quot;;
244
245             Ext.each(dd, function(d, i){
246                 re += Ext.isDate(d) ? '^' + Ext.String.escapeRegex(d.dateFormat(this.format)) + '$' : dd[i];
247                 if (i !== len) {
248                     re += '|';
249                 }
250             }, this);
251             this.disabledDatesRE = new RegExp(re + ')');
252         }
253     },
254
255 <span id='Ext-form-field-Date-method-setDisabledDates'>    /**
256 </span>     * Replaces any existing disabled dates with new values and refreshes the Date picker.
257      * @param {Array} disabledDates An array of date strings (see the &lt;tt&gt;{@link #disabledDates}&lt;/tt&gt; config
258      * for details on supported values) used to disable a pattern of dates.
259      */
260     setDisabledDates : function(dd){
261         var me = this,
262             picker = me.picker;
263             
264         me.disabledDates = dd;
265         me.initDisabledDays();
266         if (picker) {
267             picker.setDisabledDates(me.disabledDatesRE);
268         }
269     },
270
271 <span id='Ext-form-field-Date-method-setDisabledDays'>    /**
272 </span>     * Replaces any existing disabled days (by index, 0-6) with new values and refreshes the Date picker.
273      * @param {Array} disabledDays An array of disabled day indexes. See the &lt;tt&gt;{@link #disabledDays}&lt;/tt&gt;
274      * config for details on supported values.
275      */
276     setDisabledDays : function(dd){
277         var picker = this.picker;
278             
279         this.disabledDays = dd;
280         if (picker) {
281             picker.setDisabledDays(dd);
282         }
283     },
284
285 <span id='Ext-form-field-Date-method-setMinValue'>    /**
286 </span>     * Replaces any existing &lt;tt&gt;{@link #minValue}&lt;/tt&gt; with the new value and refreshes the Date picker.
287      * @param {Date} value The minimum date that can be selected
288      */
289     setMinValue : function(dt){
290         var me = this,
291             picker = me.picker,
292             minValue = (Ext.isString(dt) ? me.parseDate(dt) : dt);
293             
294         me.minValue = minValue;
295         if (picker) {
296             picker.minText = Ext.String.format(me.minText, me.formatDate(me.minValue));
297             picker.setMinDate(minValue);
298         }
299     },
300
301 <span id='Ext-form-field-Date-method-setMaxValue'>    /**
302 </span>     * Replaces any existing &lt;tt&gt;{@link #maxValue}&lt;/tt&gt; with the new value and refreshes the Date picker.
303      * @param {Date} value The maximum date that can be selected
304      */
305     setMaxValue : function(dt){
306         var me = this,
307             picker = me.picker,
308             maxValue = (Ext.isString(dt) ? me.parseDate(dt) : dt);
309             
310         me.maxValue = maxValue;
311         if (picker) {
312             picker.maxText = Ext.String.format(me.maxText, me.formatDate(me.maxValue));
313             picker.setMaxDate(maxValue);
314         }
315     },
316
317 <span id='Ext-form-field-Date-method-getErrors'>    /**
318 </span>     * Runs all of Date's validations and returns an array of any errors. Note that this first
319      * runs Text's validations, so the returned array is an amalgamation of all field errors.
320      * The additional validation checks are testing that the date format is valid, that the chosen
321      * date is within the min and max date constraints set, that the date chosen is not in the disabledDates
322      * regex and that the day chosed is not one of the disabledDays.
323      * @param {Mixed} value The value to get errors for (defaults to the current field value)
324      * @return {Array} All validation errors for this field
325      */
326     getErrors: function(value) {
327         var me = this,
328             format = Ext.String.format,
329             clearTime = Ext.Date.clearTime,
330             errors = me.callParent(arguments),
331             disabledDays = me.disabledDays,
332             disabledDatesRE = me.disabledDatesRE,
333             minValue = me.minValue,
334             maxValue = me.maxValue,
335             len = disabledDays ? disabledDays.length : 0,
336             i = 0,
337             svalue,
338             fvalue,
339             day,
340             time;
341
342         value = me.formatDate(value || me.processRawValue(me.getRawValue()));
343
344         if (value === null || value.length &lt; 1) { // if it's blank and textfield didn't flag it then it's valid
345              return errors;
346         }
347
348         svalue = value;
349         value = me.parseDate(value);
350         if (!value) {
351             errors.push(format(me.invalidText, svalue, me.format));
352             return errors;
353         }
354
355         time = value.getTime();
356         if (minValue &amp;&amp; time &lt; clearTime(minValue).getTime()) {
357             errors.push(format(me.minText, me.formatDate(minValue)));
358         }
359
360         if (maxValue &amp;&amp; time &gt; clearTime(maxValue).getTime()) {
361             errors.push(format(me.maxText, me.formatDate(maxValue)));
362         }
363
364         if (disabledDays) {
365             day = value.getDay();
366
367             for(; i &lt; len; i++) {
368                 if (day === disabledDays[i]) {
369                     errors.push(me.disabledDaysText);
370                     break;
371                 }
372             }
373         }
374
375         fvalue = me.formatDate(value);
376         if (disabledDatesRE &amp;&amp; disabledDatesRE.test(fvalue)) {
377             errors.push(format(me.disabledDatesText, fvalue));
378         }
379
380         return errors;
381     },
382
383     rawToValue: function(rawValue) {
384         return this.parseDate(rawValue) || rawValue || null;
385     },
386
387     valueToRaw: function(value) {
388         return this.formatDate(this.parseDate(value));
389     },
390
391 <span id='Ext-form-field-Date-method-setValue'>    /**
392 </span>     * Sets the value of the date field.  You can pass a date object or any string that can be
393      * parsed into a valid date, using &lt;tt&gt;{@link #format}&lt;/tt&gt; as the date format, according
394      * to the same rules as {@link Ext.Date#parse} (the default format used is &lt;tt&gt;&quot;m/d/Y&quot;&lt;/tt&gt;).
395      * &lt;br /&gt;Usage:
396      * &lt;pre&gt;&lt;code&gt;
397 //All of these calls set the same date value (May 4, 2006)
398
399 //Pass a date object:
400 var dt = new Date('5/4/2006');
401 dateField.setValue(dt);
402
403 //Pass a date string (default format):
404 dateField.setValue('05/04/2006');
405
406 //Pass a date string (custom format):
407 dateField.format = 'Y-m-d';
408 dateField.setValue('2006-05-04');
409 &lt;/code&gt;&lt;/pre&gt;
410      * @param {String/Date} date The date or valid date string
411      * @return {Ext.form.field.Date} this
412      * @method setValue
413      */
414
415 <span id='Ext-form-field-Date-method-safeParse'>    /**
416 </span>     * Attempts to parse a given string value using a given {@link Ext.Date#parse date format}.
417      * @param {String} value The value to attempt to parse
418      * @param {String} format A valid date format (see {@link Ext.Date#parse})
419      * @return {Date} The parsed Date object, or null if the value could not be successfully parsed.
420      */
421     safeParse : function(value, format) {
422         var me = this,
423             utilDate = Ext.Date,
424             parsedDate,
425             result = null;
426             
427         if (utilDate.formatContainsHourInfo(format)) {
428             // if parse format contains hour information, no DST adjustment is necessary
429             result = utilDate.parse(value, format);
430         } else {
431             // set time to 12 noon, then clear the time
432             parsedDate = utilDate.parse(value + ' ' + me.initTime, format + ' ' + me.initTimeFormat);
433             if (parsedDate) {
434                 result = utilDate.clearTime(parsedDate);
435             }
436         }
437         return result;
438     },
439     
440     // @private
441     getSubmitValue: function() {
442         var me = this,
443             format = me.submitFormat || me.format,
444             value = me.getValue();
445             
446         return value ? Ext.Date.format(value, format) : null;
447     },
448
449 <span id='Ext-form-field-Date-method-parseDate'>    /**
450 </span>     * @private
451      */
452     parseDate : function(value) {
453         if(!value || Ext.isDate(value)){
454             return value;
455         }
456
457         var me = this,
458             val = me.safeParse(value, me.format),
459             altFormats = me.altFormats,
460             altFormatsArray = me.altFormatsArray,
461             i = 0,
462             len;
463
464         if (!val &amp;&amp; altFormats) {
465             altFormatsArray = altFormatsArray || altFormats.split('|');
466             len = altFormatsArray.length;
467             for (; i &lt; len &amp;&amp; !val; ++i) {
468                 val = me.safeParse(value, altFormatsArray[i]);
469             }
470         }
471         return val;
472     },
473
474     // private
475     formatDate : function(date){
476         return Ext.isDate(date) ? Ext.Date.dateFormat(date, this.format) : date;
477     },
478
479     createPicker: function() {
480         var me = this,
481             format = Ext.String.format;
482
483         return Ext.create('Ext.picker.Date', {
484             ownerCt: me.ownerCt,
485             renderTo: document.body,
486             floating: true,
487             hidden: true,
488             focusOnShow: true,
489             minDate: me.minValue,
490             maxDate: me.maxValue,
491             disabledDatesRE: me.disabledDatesRE,
492             disabledDatesText: me.disabledDatesText,
493             disabledDays: me.disabledDays,
494             disabledDaysText: me.disabledDaysText,
495             format: me.format,
496             showToday: me.showToday,
497             startDay: me.startDay,
498             minText: format(me.minText, me.formatDate(me.minValue)),
499             maxText: format(me.maxText, me.formatDate(me.maxValue)),
500             listeners: {
501                 scope: me,
502                 select: me.onSelect
503             },
504             keyNavConfig: {
505                 esc: function() {
506                     me.collapse();
507                 }
508             }
509         });
510     },
511
512     onSelect: function(m, d) {
513         var me = this;
514         
515         me.setValue(d);
516         me.fireEvent('select', me, d);
517         me.collapse();
518     },
519
520 <span id='Ext-form-field-Date-method-onExpand'>    /**
521 </span>     * @private
522      * Sets the Date picker's value to match the current field value when expanding.
523      */
524     onExpand: function() {
525         var me = this,
526             value = me.getValue();
527         me.picker.setValue(Ext.isDate(value) ? value : new Date());
528     },
529
530 <span id='Ext-form-field-Date-method-onCollapse'>    /**
531 </span>     * @private
532      * Focuses the field when collapsing the Date picker.
533      */
534     onCollapse: function() {
535         this.focus(false, 60);
536     },
537
538     // private
539     beforeBlur : function(){
540         var me = this,
541             v = me.parseDate(me.getRawValue()),
542             focusTask = me.focusTask;
543         
544         if (focusTask) {
545             focusTask.cancel();
546         }
547         
548         if (v) {
549             me.setValue(v);
550         }
551     }
552
553 <span id='Ext-form-field-Date-cfg-grow'>    /**
554 </span>     * @cfg {Boolean} grow @hide
555      */
556 <span id='Ext-form-field-Date-cfg-growMin'>    /**
557 </span>     * @cfg {Number} growMin @hide
558      */
559 <span id='Ext-form-field-Date-cfg-growMax'>    /**
560 </span>     * @cfg {Number} growMax @hide
561      */
562 <span id='Ext-form-field-Date-method-autoSize'>    /**
563 </span>     * @hide
564      * @method autoSize
565      */
566 });
567 </pre>
568 </body>
569 </html>