Roo/form/ComboBoxArray.js
[roojs1] / Roo / form / DateField.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  * @class Roo.form.DateField
14  * @extends Roo.form.TriggerField
15  * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
16 * @constructor
17 * Create a new DateField
18 * @param {Object} config
19  */
20 Roo.form.DateField = function(config){
21     Roo.form.DateField.superclass.constructor.call(this, config);
22     
23       this.addEvents({
24          
25         /**
26          * @event select
27          * Fires when a date is selected
28              * @param {Roo.form.DateField} combo This combo box
29              * @param {Date} date The date selected
30              */
31         'select' : true
32          
33     });
34     
35     
36     if(typeof this.minValue == "string") {
37         this.minValue = this.parseDate(this.minValue);
38     }
39     if(typeof this.maxValue == "string") {
40         this.maxValue = this.parseDate(this.maxValue);
41     }
42     this.ddMatch = null;
43     if(this.disabledDates){
44         var dd = this.disabledDates;
45         var re = "(?:";
46         for(var i = 0; i < dd.length; i++){
47             re += dd[i];
48             if(i != dd.length-1) {
49                 re += "|";
50             }
51         }
52         this.ddMatch = new RegExp(re + ")");
53     }
54 };
55
56 Roo.extend(Roo.form.DateField, Roo.form.TriggerField,  {
57     /**
58      * @cfg {String} format
59      * The default date format string which can be overriden for localization support.  The format must be
60      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
61      */
62     format : "m/d/y",
63     /**
64      * @cfg {String} altFormats
65      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
66      * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
67      */
68     altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
69     /**
70      * @cfg {Array} disabledDays
71      * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
72      */
73     disabledDays : null,
74     /**
75      * @cfg {String} disabledDaysText
76      * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
77      */
78     disabledDaysText : "Disabled",
79     /**
80      * @cfg {Array} disabledDates
81      * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
82      * expression so they are very powerful. Some examples:
83      * <ul>
84      * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
85      * <li>["03/08", "09/16"] would disable those days for every year</li>
86      * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
87      * <li>["03/../2006"] would disable every day in March 2006</li>
88      * <li>["^03"] would disable every day in every March</li>
89      * </ul>
90      * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
91      * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
92      */
93     disabledDates : null,
94     /**
95      * @cfg {String} disabledDatesText
96      * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
97      */
98     disabledDatesText : "Disabled",
99     /**
100      * @cfg {Date/String} minValue
101      * The minimum allowed date. Can be either a Javascript date object or a string date in a
102      * valid format (defaults to null).
103      */
104     minValue : null,
105     /**
106      * @cfg {Date/String} maxValue
107      * The maximum allowed date. Can be either a Javascript date object or a string date in a
108      * valid format (defaults to null).
109      */
110     maxValue : null,
111     /**
112      * @cfg {String} minText
113      * The error text to display when the date in the cell is before minValue (defaults to
114      * 'The date in this field must be after {minValue}').
115      */
116     minText : "The date in this field must be equal to or after {0}",
117     /**
118      * @cfg {String} maxText
119      * The error text to display when the date in the cell is after maxValue (defaults to
120      * 'The date in this field must be before {maxValue}').
121      */
122     maxText : "The date in this field must be equal to or before {0}",
123     /**
124      * @cfg {String} invalidText
125      * The error text to display when the date in the field is invalid (defaults to
126      * '{value} is not a valid date - it must be in the format {format}').
127      */
128     invalidText : "{0} is not a valid date - it must be in the format {1}",
129     /**
130      * @cfg {String} triggerClass
131      * An additional CSS class used to style the trigger button.  The trigger will always get the
132      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
133      * which displays a calendar icon).
134      */
135     triggerClass : 'x-form-date-trigger',
136     
137
138     /**
139      * @cfg {Boolean} useIso
140      * if enabled, then the date field will use a hidden field to store the 
141      * real value as iso formated date. default (false)
142      */ 
143     useIso : false,
144     /**
145      * @cfg {String/Object} autoCreate
146      * A DomHelper element spec, or true for a default element spec (defaults to
147      * {tag: "input", type: "text", size: "10", autocomplete: "off"})
148      */ 
149     // private
150     defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
151     
152     // private
153     hiddenField: false,
154     
155     onRender : function(ct, position)
156     {
157         Roo.form.DateField.superclass.onRender.call(this, ct, position);
158         if (this.useIso) {
159             //this.el.dom.removeAttribute('name'); 
160             Roo.log("Changing name?");
161             this.el.dom.setAttribute('name', this.name + '____hidden___' ); 
162             this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
163                     'before', true);
164             this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
165             // prevent input submission
166             this.hiddenName = this.name;
167         }
168             
169             
170     },
171     
172     // private
173     validateValue : function(value)
174     {
175         value = this.formatDate(value);
176         if(!Roo.form.DateField.superclass.validateValue.call(this, value)){
177             Roo.log('super failed');
178             return false;
179         }
180         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
181              return true;
182         }
183         var svalue = value;
184         value = this.parseDate(value);
185         if(!value){
186             Roo.log('parse date failed' + svalue);
187             this.markInvalid(String.format(this.invalidText, svalue, this.format));
188             return false;
189         }
190         var time = value.getTime();
191         if(this.minValue && time < this.minValue.getTime()){
192             this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
193             return false;
194         }
195         if(this.maxValue && time > this.maxValue.getTime()){
196             this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
197             return false;
198         }
199         if(this.disabledDays){
200             var day = value.getDay();
201             for(var i = 0; i < this.disabledDays.length; i++) {
202                 if(day === this.disabledDays[i]){
203                     this.markInvalid(this.disabledDaysText);
204                     return false;
205                 }
206             }
207         }
208         var fvalue = this.formatDate(value);
209         if(this.ddMatch && this.ddMatch.test(fvalue)){
210             this.markInvalid(String.format(this.disabledDatesText, fvalue));
211             return false;
212         }
213         return true;
214     },
215
216     // private
217     // Provides logic to override the default TriggerField.validateBlur which just returns true
218     validateBlur : function(){
219         return !this.menu || !this.menu.isVisible();
220     },
221     
222     getName: function()
223     {
224         // returns hidden if it's set..
225         if (!this.rendered) {return ''};
226         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
227         
228     },
229
230     /**
231      * Returns the current date value of the date field.
232      * @return {Date} The date value
233      */
234     getValue : function(){
235         
236         return  this.hiddenField ?
237                 this.hiddenField.value :
238                 this.parseDate(Roo.form.DateField.superclass.getValue.call(this)) || "";
239     },
240
241     /**
242      * Sets the value of the date field.  You can pass a date object or any string that can be parsed into a valid
243      * date, using DateField.format as the date format, according to the same rules as {@link Date#parseDate}
244      * (the default format used is "m/d/y").
245      * <br />Usage:
246      * <pre><code>
247 //All of these calls set the same date value (May 4, 2006)
248
249 //Pass a date object:
250 var dt = new Date('5/4/06');
251 dateField.setValue(dt);
252
253 //Pass a date string (default format):
254 dateField.setValue('5/4/06');
255
256 //Pass a date string (custom format):
257 dateField.format = 'Y-m-d';
258 dateField.setValue('2006-5-4');
259 </code></pre>
260      * @param {String/Date} date The date or valid date string
261      */
262     setValue : function(date){
263         if (this.hiddenField) {
264             this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
265         }
266         Roo.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
267         // make sure the value field is always stored as a date..
268         this.value = this.parseDate(date);
269         
270         
271     },
272
273     // private
274     parseDate : function(value){
275         if(!value || value instanceof Date){
276             return value;
277         }
278         var v = Date.parseDate(value, this.format);
279          if (!v && this.useIso) {
280             v = Date.parseDate(value, 'Y-m-d');
281         }
282         if(!v && this.altFormats){
283             if(!this.altFormatsArray){
284                 this.altFormatsArray = this.altFormats.split("|");
285             }
286             for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
287                 v = Date.parseDate(value, this.altFormatsArray[i]);
288             }
289         }
290         return v;
291     },
292
293     // private
294     formatDate : function(date, fmt){
295         return (!date || !(date instanceof Date)) ?
296                date : date.dateFormat(fmt || this.format);
297     },
298
299     // private
300     menuListeners : {
301         select: function(m, d){
302             
303             this.setValue(d);
304             this.fireEvent('select', this, d);
305         },
306         show : function(){ // retain focus styling
307             this.onFocus();
308         },
309         hide : function(){
310             this.focus.defer(10, this);
311             var ml = this.menuListeners;
312             this.menu.un("select", ml.select,  this);
313             this.menu.un("show", ml.show,  this);
314             this.menu.un("hide", ml.hide,  this);
315         }
316     },
317
318     // private
319     // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
320     onTriggerClick : function(){
321         if(this.disabled){
322             return;
323         }
324         if(this.menu == null){
325             this.menu = new Roo.menu.DateMenu();
326         }
327         Roo.apply(this.menu.picker,  {
328             showClear: this.allowBlank,
329             minDate : this.minValue,
330             maxDate : this.maxValue,
331             disabledDatesRE : this.ddMatch,
332             disabledDatesText : this.disabledDatesText,
333             disabledDays : this.disabledDays,
334             disabledDaysText : this.disabledDaysText,
335             format : this.useIso ? 'Y-m-d' : this.format,
336             minText : String.format(this.minText, this.formatDate(this.minValue)),
337             maxText : String.format(this.maxText, this.formatDate(this.maxValue))
338         });
339         this.menu.on(Roo.apply({}, this.menuListeners, {
340             scope:this
341         }));
342         this.menu.picker.setValue(this.getValue() || new Date());
343         this.menu.show(this.el, "tl-bl?");
344     },
345
346     beforeBlur : function(){
347         var v = this.parseDate(this.getRawValue());
348         if(v){
349             this.setValue(v);
350         }
351     },
352
353     /*@
354      * overide
355      * 
356      */
357     isDirty : function() {
358         if(this.disabled) {
359             return false;
360         }
361         
362         if(typeof(this.startValue) === 'undefined'){
363             return false;
364         }
365         
366         return String(this.getValue()) !== String(this.startValue);
367         
368     }
369 });