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