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