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