Remove invalid_value class before validation
[phpmyadmin/alexukf.git] / js / tbl_change.js
blob896700bb63445337808ed81199c9250309710b3b
1 /* vim: set expandtab sw=4 ts=4 sts=4: */
2 /**
3  * @fileoverview    function used in table data manipulation pages
4  *
5  * @requires    jQuery
6  * @requires    jQueryUI
7  * @requires    js/functions.js
8  *
9  */
11 /**
12  * Modify form controls when the "NULL" checkbox is checked
13  *
14  * @param   theType     string   the MySQL field type
15  * @param   urlField    string   the urlencoded field name - OBSOLETE
16  * @param   md5Field    string   the md5 hashed field name
17  * @param   multi_edit  string   the multi_edit row sequence number
18  *
19  * @return  boolean  always true
20  */
21 function nullify(theType, urlField, md5Field, multi_edit)
23     var rowForm = document.forms['insertForm'];
25     if (typeof(rowForm.elements['funcs' + multi_edit + '[' + md5Field + ']']) != 'undefined') {
26         rowForm.elements['funcs' + multi_edit + '[' + md5Field + ']'].selectedIndex = -1;
27     }
29     // "SET" field , "ENUM" field with more than 20 characters
30     // or foreign key field (drop-down)
31     if (theType == 1 || theType == 3 || theType == 4) {
32         rowForm.elements['field_' + md5Field + multi_edit + '[]'].selectedIndex = -1;
33     }
34     // Other "ENUM" field
35     else if (theType == 2) {
36         var elts     = rowForm.elements['field_' + md5Field + multi_edit + '[]'];
37         // when there is just one option in ENUM:
38         if (elts.checked) {
39             elts.checked = false;
40         } else {
41             var elts_cnt = elts.length;
42             for (var i = 0; i < elts_cnt; i++ ) {
43                 elts[i].checked = false;
44             } // end for
46         } // end if
47     }
48     // foreign key field (with browsing icon for foreign values)
49     else if (theType == 6) {
50         rowForm.elements['field_' + md5Field + multi_edit + '[]'].value = '';
51     }
52     // Other field types
53     else /*if (theType == 5)*/ {
54         rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'].value = '';
55     } // end if... else if... else
57     return true;
58 } // end of the 'nullify()' function
61 /**
62  * javascript DateTime format validation.
63  * its used to prevent adding default (0000-00-00 00:00:00) to database when user enter wrong values
64  * Start of validation part
65  */
66 //function checks the number of days in febuary
67 function daysInFebruary (year){
68     return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
70 //function to convert single digit to double digit
71 function fractionReplace(num)
73     num=parseInt(num);
74     var res="00";
75     switch(num)
76     {
77         case 1:res= "01";break;
78         case 2:res= "02";break;
79         case 3:res= "03";break;
80         case 4:res= "04";break;
81         case 5:res= "05";break;
82         case 6:res= "06";break;
83         case 7:res= "07";break;
84         case 8:res= "08";break;
85         case 9:res= "09";break;
86         }
87     return res;
90 /* function to check the validity of date
91 * The following patterns are accepted in this validation (accepted in mysql as well)
92 * 1) 2001-12-23
93 * 2) 2001-1-2
94 * 3) 02-12-23
95 * 4) And instead of using '-' the following punctuations can be used (+,.,*,^,@,/) All these are accepted by mysql as well. Therefore no issues
97 function isDate(val,tmstmp)
99     val=val.replace(/[.|*|^|+|//|@]/g,'-');
100     var arrayVal=val.split("-");
101     for(var a=0;a<arrayVal.length;a++)
102     {
103         if(arrayVal[a].length==1)
104             arrayVal[a]=fractionReplace(arrayVal[a]);
105     }
106     val=arrayVal.join("-");
107     var pos=2;
108             dtexp=new RegExp(/^([0-9]{4})-(((01|03|05|07|08|10|12)-((0[0-9])|([1-2][0-9])|(3[0-1])))|((02|04|06|09|11)-((0[0-9])|([1-2][0-9])|30)))$/);
109         if(val.length==8)
110         {
111             dtexp=new RegExp(/^([0-9]{2})-(((01|03|05|07|08|10|12)-((0[0-9])|([1-2][0-9])|(3[0-1])))|((02|04|06|09|11)-((0[0-9])|([1-2][0-9])|30)))$/);
112             pos=0;
113         }
114         if(dtexp.test(val))
115         {
116             var month=parseInt(val.substring(pos+3,pos+5));
117             var day=parseInt(val.substring(pos+6,pos+8));
118             var year=parseInt(val.substring(0,pos+2));
119             if(month==2&&day>daysInFebruary(year))
120                 return false;
121             if(val.substring(0,pos+2).length==2)
122             {
123                 if(val.substring(0,pos+2).length==2)
124                     year=parseInt("20"+val.substring(0,pos+2));
125                 else
126                     year=parseInt("19"+val.substring(0,pos+2));
127             }
128             if(tmstmp==true)
129             {
130                 if(year<1978) return false;
131                 if(year>2038||(year>2037&&day>19&&month>=1)||(year>2037&&month>1)) return false;
132                 }
133         }
134         else
135             return false;
136         return true;
139 /* function to check the validity of time
140 * The following patterns are accepted in this validation (accepted in mysql as well)
141 * 1) 2:3:4
142 * 2) 2:23:43
144 function isTime(val)
146     var arrayVal=val.split(":");
147     for(var a=0;a<arrayVal.length;a++)
148     {
149         if(arrayVal[a].length==1)
150             arrayVal[a]=fractionReplace(arrayVal[a]);
151     }
152     val=arrayVal.join(":");
153     tmexp=new RegExp(/^(([0-1][0-9])|(2[0-3])):((0[0-9])|([1-5][0-9])):((0[0-9])|([1-5][0-9]))$/);
154         if(!tmexp.test(val))
155             return false;
156         return true;
159 function verificationsAfterFieldChange(urlField, multi_edit, theType){
160     var evt = window.event || arguments.callee.caller.arguments[0];
161     var target = evt.target || evt.srcElement;
163     // Unchecks the corresponding "NULL" control
164     $("input[name='fields_null[multi_edit][" + multi_edit + "][" + urlField + "]']").attr({'checked': false});
166     // Unchecks the Ignore checkbox for the current row
167     $("input[name='insert_ignore_" + multi_edit + "']").attr({'checked': false});
168     var $this_input = $("input[name='fields[multi_edit][" + multi_edit + "][" + urlField + "]']");
170     // Does this field come from datepicker?
171     if ($this_input.data('comes_from') == 'datepicker') {
172         // Yes, so do not validate because the final value is not yet in
173         // the field and hopefully the datepicker returns a valid date+time
174         $this_input.data('comes_from', '');
175         return true;
176     }
178     if(target.name.substring(0,6)=="fields") {
179         // validate for date time
180         if(theType=="datetime"||theType=="time"||theType=="date"||theType=="timestamp") {
181             $this_input.removeClass("invalid_value");
182             var dt_value = $this_input.val();
183             if(theType=="date"){
184                 if (! isDate(dt_value)) {
185                     $this_input.addClass("invalid_value");
186                     return false;
187                 }
188             } else if(theType=="time") {
189                 if (! isTime(dt_value)) {
190                     $this_input.addClass("invalid_value");
191                     return false;
192                 }
193             } else if(theType=="datetime"||theType=="timestamp") {
194                 tmstmp=false;
195                 if(dt_value == "CURRENT_TIMESTAMP") {
196                     return true;
197                 }
198                 if(theType=="timestamp") {
199                     tmstmp=true;
200                 }
201                 if(dt_value=="0000-00-00 00:00:00") {
202                     return true;
203                 }
204                 var dv=dt_value.indexOf(" ");
205                 if(dv==-1) {
206                     $this_input.addClass("invalid_value");
207                     return false;
208                 } else {
209                     if (! (isDate(dt_value.substring(0,dv),tmstmp) && isTime(dt_value.substring(dv+1)))) {
210                         $this_input.addClass("invalid_value");
211                         return false;
212                     }
213                 }
214             }
215         }
216         //validate for integer type
217         if(theType.substring(0,3) == "int"){
218             $this_input.removeClass("invalid_value");
219             if(isNaN($this_input.val())){
220                 $this_input.addClass("invalid_value");
221                 return false;
222             }
223         }
224     }
226  /* End of datetime validation*/
229  * Ajax handlers for Change Table page
231  * Actions Ajaxified here:
232  * Submit Data to be inserted into the table
233  * Restart insertion with 'N' rows.
234  */
235 $(document).ready(function() {
237     // these were hidden via the "hide" class
238     $('.foreign_values_anchor').show();
240     /**
241      * Handles all current checkboxes for Null; this only takes care of the
242      * checkboxes on currently displayed rows as the rows generated by 
243      * "Continue insertion" are handled in the "Continue insertion" code 
244      * 
245      */
246     $('.checkbox_null').bind('click', function(e) {
247             nullify(
248                 // use hidden fields populated by tbl_change.php
249                 $(this).siblings('.nullify_code').val(),
250                 $(this).closest('tr').find('input:hidden').first().val(), 
251                 $(this).siblings('.hashed_field').val(),
252                 $(this).siblings('.multi_edit').val()
253             );
254     });
256     /**
257      * Submission of data to be inserted or updated 
258      * 
259      * @uses    PMA_ajaxShowMessage()
260      *
261      * This section has been deactivated. Here are the problems that I've
262      * noticed:
263      *
264      * 1. If the form contains a file upload field, the data does not reach
265      *    tbl_replace.php. This is because AJAX does not support file upload.
266      *    As a workaround I tried jquery.form.js version 2.49. The file
267      *    upload worked but afterwards the browser presented a tbl_replace.php
268      *    file and a choice to open or save.
269      *
270      * 2. This code can be called if we are editing or inserting. If editing,
271      *    the "and then" action can be "go back to this page" or "edit next
272      *    row", in which cases it makes sense to use AJAX. But the "go back
273      *    to previous page" and "insert another new row" actions, using AJAX 
274      *    has no obvious advantage. If inserting, the "go back to previous"
275      *    action needs a page refresh anyway. 
276      */
277     $("#insertFormDEACTIVATED").live('submit', function(event) {
279         /**
280          * @var the_form    Object referring to the insertion form
281          */
282         var $form = $(this);
283         event.preventDefault();
285         PMA_ajaxShowMessage();
286         PMA_prepareForAjaxRequest($form);
288         $.post($form.attr('action'), $form.serialize(), function(data) {
289             if (typeof data.success != 'undefined') {
290                 if(data.success == true) {
291                     PMA_ajaxShowMessage(data.message);
293                     $("#topmenucontainer")
294                     .next('div')
295                     .remove()
296                     .end()
297                     .after(data.sql_query);
299                     //Remove the empty notice div generated due to a NULL query passed to PMA_showMessage()
300                     var $notice_class = $("#topmenucontainer").next("div").find('.notice');
301                     if ($notice_class.text() == '') {
302                         $notice_class.remove();
303                     }
305                     var submit_type = $form.find("select[name='submit_type']").val();
306                     if ('insert' == submit_type || 'insertignore' == submit_type) {
307                         //Clear the data in the forms
308                         $form.find('input:reset').trigger('click');
309                     }
310                 } else {
311                     PMA_ajaxShowMessage(PMA_messages['strErrorProcessingRequest'] + " : "+data.error, "7000");
312                 }
313             } else {
314                 //happens for example when no change was done while editing
315                 $('#insertForm').remove();
316                 $('#topmenucontainer').after('<div id="sqlqueryresults"></div>');
317                 $('#sqlqueryresults').html(data);
318             }
319         })
320     }) // end submission of data to be inserted into table
322     /**
323      * Continue Insertion form
324      */
325     $("#insert_rows").live('change', function(event) {
326         event.preventDefault();
328         /**
329          * @var curr_rows   Number of current insert rows already on page
330          */
331         var curr_rows = $(".insertRowTable").length;
332         /**
333          * @var target_rows Number of rows the user wants
334          */
335         var target_rows = $("#insert_rows").val();
337         // remove all datepickers
338         $('.datefield,.datetimefield').each(function(){
339             $(this).datepicker('destroy');
340         });
342         if(curr_rows < target_rows ) {
343             while( curr_rows < target_rows ) {
345                 /**
346                  * @var $last_row    Object referring to the last row
347                  */
348                 var $last_row = $("#insertForm").find(".insertRowTable:last");
350                 // need to access this at more than one level
351                 // (also needs improvement because it should be calculated
352                 //  just once per cloned row, not once per column)
353                 var new_row_index = 0;
355                 //Clone the insert tables
356                 $last_row
357                 .clone()
358                 .insertBefore("#actions_panel")
359                 .find('input[name*=multi_edit],select[name*=multi_edit],textarea[name*=multi_edit]')
360                 .each(function() {
362                     var $this_element = $(this);
363                     /**
364                      * Extract the index from the name attribute for all input/select fields and increment it
365                      * name is of format funcs[multi_edit][10][<long random string of alphanum chars>]
366                      */
368                     /**
369                      * @var this_name   String containing name of the input/select elements
370                      */
371                     var this_name = $this_element.attr('name');
372                     /** split {@link this_name} at [10], so we have the parts that can be concatenated later */
373                     var name_parts = this_name.split(/\[\d+\]/);
374                     /** extract the [10] from  {@link name_parts} */
375                     var old_row_index_string = this_name.match(/\[\d+\]/)[0];
376                     /** extract 10 - had to split into two steps to accomodate double digits */
377                     var old_row_index = parseInt(old_row_index_string.match(/\d+/)[0]);
379                     /** calculate next index i.e. 11 */
380                     new_row_index = old_row_index + 1;
381                     /** generate the new name i.e. funcs[multi_edit][11][foobarbaz] */
382                     var new_name = name_parts[0] + '[' + new_row_index + ']' + name_parts[1];
384                     var hashed_field = name_parts[1].match(/\[(.+)\]/)[1];
385                     $this_element.attr('name', new_name);
387                     if ($this_element.is('.textfield')) {
388                         // do not remove the 'value' attribute for ENUM columns
389                         if ($this_element.closest('tr').find('span.column_type').html() != 'enum') {
390                             $this_element.attr('value', '');
391                         }
392                         $this_element
393                         .unbind('change')
394                         // Remove onchange attribute that was placed
395                         // by tbl_change.php; it refers to the wrong row index
396                         .attr('onchange', null)
397                         // Keep these values to be used when the element
398                         // will change
399                         .data('hashed_field', hashed_field)
400                         .data('new_row_index', new_row_index)
401                         .bind('change', function(e) {
402                             var $changed_element = $(this);
403                             verificationsAfterFieldChange(
404                                 $changed_element.data('hashed_field'), 
405                                 $changed_element.data('new_row_index'), 
406                                 $changed_element.closest('tr').find('span.column_type').html()
407                                 );
408                         });
409                     }
411                     if ($this_element.is('.checkbox_null')) {
412                         $this_element
413                         // this event was bound earlier by jQuery but
414                         // to the original row, not the cloned one, so unbind()
415                         .unbind('click')
416                         // Keep these values to be used when the element
417                         // will be clicked 
418                         .data('hashed_field', hashed_field)
419                         .data('new_row_index', new_row_index)
420                         .bind('click', function(e) {
421                                 var $changed_element = $(this);
422                                 nullify(
423                                     $changed_element.siblings('.nullify_code').val(),
424                                     $this_element.closest('tr').find('input:hidden').first().val(), 
425                                     $changed_element.data('hashed_field'), 
426                                     '[multi_edit][' + $changed_element.data('new_row_index') + ']'
427                                     );
428                         });
429                     }
430                 }) // end each
431                 .end()
432                 .find('.foreign_values_anchor')
433                 .each(function() {
434                         $anchor = $(this);
435                         var new_value = 'rownumber=' + new_row_index;
436                         // needs improvement in case something else inside
437                         // the href contains this pattern
438                         var new_href = $anchor.attr('href').replace(/rownumber=\d+/, new_value);
439                         $anchor.attr('href', new_href );
440                     });
442                 //Insert/Clone the ignore checkboxes
443                 if(curr_rows == 1 ) {
444                     $('<input id="insert_ignore_1" type="checkbox" name="insert_ignore_1" checked="checked" />')
445                     .insertBefore(".insertRowTable:last")
446                     .after('<label for="insert_ignore_1">' + PMA_messages['strIgnore'] + '</label>');
447                 }
448                 else {
450                     /**
451                      * @var last_checkbox   Object reference to the last checkbox in #insertForm
452                      */
453                     var last_checkbox = $("#insertForm").children('input:checkbox:last');
455                     /** name of {@link last_checkbox} */
456                     var last_checkbox_name = $(last_checkbox).attr('name');
457                     /** index of {@link last_checkbox} */
458                     var last_checkbox_index = parseInt(last_checkbox_name.match(/\d+/));
459                     /** name of new {@link last_checkbox} */
460                     var new_name = last_checkbox_name.replace(/\d+/,last_checkbox_index+1);
462                     $(last_checkbox)
463                     .clone()
464                     .attr({'id':new_name, 'name': new_name, 'checked': true})
465                     .add('label[for^=insert_ignore]:last')
466                     .clone()
467                     .attr('for', new_name)
468                     .before('<br />')
469                     .insertBefore(".insertRowTable:last");
470                 }
471                 curr_rows++;
472             }
473         // recompute tabindex for text fields and other controls at footer;
474         // IMO it's not really important to handle the tabindex for
475         // function and Null
476         var tabindex = 0;
477         $('.textfield') 
478         .each(function() {
479                 tabindex++;
480                 $(this).attr('tabindex', tabindex);
481                 // update the IDs of textfields to ensure that they are unique
482                 $(this).attr('id', "field_" + tabindex + "_3");
483             });
484         $('.control_at_footer')
485         .each(function() {
486                 tabindex++;
487                 $(this).attr('tabindex', tabindex);
488             });
489         // Add all the required datepickers back
490         $('.datefield,.datetimefield').each(function(){
491             PMA_addDatepicker($(this));
492             });
493         }
494         else if( curr_rows > target_rows) {
495             while(curr_rows > target_rows) {
496                 $("input[id^=insert_ignore]:last")
497                 .nextUntil("fieldset")
498                 .andSelf()
499                 .remove();
500                 curr_rows--;
501             }
502         }
503     })
504 }, 'top.frame_content'); //end $(document).ready()