how to use monthNames in jqgrid when validating date? - validation

In my jqgrid when i am clicking on add new record i have date field prepopulated with current date. Format of the date is yyyy-MMM-d (e.g. 2010-Jan-23).
Date is required field and when i click submit button it fails validation and displays error that this date is invalid, and it wants Y-m-d format.
How can i check my value with jqgrid? In other words how to make jqgrid accept the following date format when validating 2010-Jan-23?
Thanks.
Here is my JSON data:
{"rows":[
{"id":1,"cell":["2010-Mar-3","Pepto","2","False","not active"]},
{"id":2,"cell":["2009-May-6","Tylenol","5","False","not active"]},
{"id":3,"cell":["2008-May-6","Aspirin","9","True","active"]}
]}},
Here is my date column definition:
{ name: 'Date',
index: 'date',
width: '80px',
align: 'center',
sortable: false,
editable: true,
datefmt: 'Y-M-d',
editoptions: { dataInit: function(elem) { $(elem).datepicker({ dateFormat: 'yy-M-d' });},value: getDate } ,
editrules: { required: true, date:true} },
The getdate function inserts current date into field. here is the function:
function getDate(){
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var now = new Date();
return now.getFullYear() + "-" + monthNames[now.getMonth()] + "-" + now.getDate();
}
Maybe this is because of this function? Can i insert current date from datepicker?
Amount of data sent from the server is not too big (about 10-30 rows) and this application will be used by maximum of 50 people, so there is no concerns regarding amounts of data.
Anytime when i have value as 2010-Jun-23 in the field, i get error message:Enter valid date value - Y-M-d

Verify that you defined datefmt: 'Y-M-d' in the column definition of colModel. In the list of editrules options (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:common_rules#editrules) is defined that if you use date: true as a editrules option, the validation will be done corresponds with the datefmt option.
Some more recommendations if you use date in jqGrid:
If you not yet use, think about of the usage of jQuery.datepicker (see http://jqueryui.com/demos/datepicker/#date-formats) inside of dataInit function of editoptions (like
editoptions: {
dataInit : function (elem) {
$(elem).datepicker();
}
// ...
}
in the simplest case). If you use searching for date fields, you can use dataInit with jQuery.datepicker also in searchoptions in the same way (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:singe_searching#colmodel_options). The usage of jQuery.datepicker in jqGrid is very easy, but it makes your program more comfortable.
Usage of standard date formatter (formatter: 'date') can be useful to convert source data format send to jqGrid to the new format which will be displayed. For example,
formatter: 'date', formatoptions: {srcformat:'y-m-d', newformat: 'Y-M-d' }
It is less interesting, but it can reduce a little the size of data send from server to client.
UPDATED: I must admit, I don't tested my suggestion with exactly your data format. Just now I tested all one more time and then read carefully jqGrid documentation about datefmt (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:colmodel_options). For datefmt are only numerical format for months is supported! So the value at the time of date verification must be in a numerical format. What can we do? For example following
we define as parameters of navGrid function "add" parameters (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:navigator parameter prmAdd) like following:
{ beforeCheckValues: function(posdata, formid, mode) {
var data = posdata.Date;
var dateParts = data.split("-");
var mounth = dateParts[1];
var mounths = $.jgrid.formatter.date.monthNames;
var iMounth = -1;
for (var i=0; i<12; i++) {
if (mounth === mounths[i]) {
iMounth = i;
break;
}
}
if (iMounth !== -1) {
posdata.Date = dateParts[0]+'-'+(iMounth+1)+'-'+dateParts[2];
}
},
beforeSubmit: function(postdata, formid) {
var data = postdata.Date;
var dateParts = data.split("-");
var mounths = $.jgrid.formatter.date.monthNames;
postdata.Date = dateParts[0]+'-'+
$.jgrid.formatter.date.monthNames[dateParts[1]-1]+
'-'+dateParts[2];
return [true,""];
}
}
So we convert the Date field to the numerical format inside of beforeCheckValues function and then convert all back to the original format (like 2010-Jan-23) after usage of checkDate. It will work.
The main question is now: have we some advantage from such kind of the date checking? We can just don't use editrules: { date:true } and implement our own date checking inside of beforeSubmit function. If we find out the wrong date we should return [false,"My error message"] and our custom error message "My error message" will be displayed by jqGrid.
So the easiest solution of your problem we receive if we could change the date format to any numerical form (Y-mm-d, mm/d/Y or another one). Usage of datepicker will makes for users the format problem not very important. Think about this and choose the way which your prefer.

I was facing similar issue. I have resolved it using custom function for validation. I am suing date format as '23-Jan-05'. You may modify it to suit your required date format.
function datecheck(value, colname) {
var dateParts = value.split("-");
var datePart = dateParts[0];
var mounth = dateParts[1];
var yearPart = dateParts[2];
var mounths = $.jgrid.formatter.date.monthNames;
var monthPart = -1;
for (var i = 0; i < 12; i++) {
if (mounth === mounths[i]) {
monthPart = i + 1;
break;
}
}
var dateText = monthPart + '-' + datePart + '-' + yearPart;
var date = Date.parse(dateText);
if (isNaN(date))
return [false,"Invalid date. Format expected: dd-mmm-yy. (23-Jul-05)"];
else
return [true,""];
}
JQGrid column details:
colModel: [name: 'JoiningDate', align: "center", editable: true,
editrules: { custom: true, custom_func: datecheck },
formatter: 'date', formatoptions: { srcformat: 'y-m-d', newformat: 'd-M-y' }, edittype: 'text', editable: true,
editoptions: { dataInit: function (el) { setTimeout(function () { $(el).datepicker({ dateFormat: 'd-M-y' }); }, 200); } }
},
Hope this helps.
Regards,
Abhilash

Related

Jqgrid Masking phone number should save in the same format and position

I'm using jquery.jqgrid version v4.4.4, mvc 5.
In my inline jqgrid, i have Phone Number colModel need to be mask in US Phone number format and my code looks like,
{
name: 'PhoneNumber', index: 'PhoneNumber', editable: true, sortable: true, width: 300, classes: "grid-col",
editoptions: { dataInit: function (elem) {
$(elem).mask("?(999) 999-9999");
$(this).val(elem);
}
}
},
If i type like this'(454)453-3233' the field(textbox) holds the correct value and get saved as '4544533233' in database correctly. To remove the brackets and hypen i used,
PhoneNumber = PhoneNumber.replace(/\D/g, ''); //Removes anything that is not a digit \D
The issue is,
First,if i type like this '( 54)4 - 65' then the field formatted itself and holds (544)65 which is wrong.
Second, the existing phone numbers are not masked, displays in the grid without mask format.
1).How to make the field to hold and save the input with same position as i typed?
2).How to display the existing Phone Number('4544533233'stored like this in db) in mask format?
Thanks.
colModel[{ name: 'DOB', width: 75, editable: true, formatter: dateFormatter, editoptions: { class: 'isDateField' } }]
//dateFormatter function to format before saving
function dateFormatter(cellvalue, options, rowObject) {
if (cellvalue !== undefined) {
var formattedValue = (cellvalue.slice(0, 4) + '/' + cellvalue.slice(4, 6) + '/' + cellvalue.slice(6, 8));
if (formattedValue==='//') {
return ('');
}
return formattedValue;
}
};

Date format in SlickGrid

SlickGrid launches the calendar using a default US date format of mm/dd/yyyy. I store dates in my database in Australian format dd/mm/yyyy. how can I change the format of the calendar to take dd/mm/yyyy?
You can use the DatePicker of your choice by writing a new custom editor. The default date editor uses jQueryUI DatePicker.
Personally (I'm in Australia too), I use the default with the following settings:
function DateFormatter(rowIndex, cell, value, columnDef, grid, dataProvider) {
if (value == null || value === "") { return "-"; }
return moment.utc(value).format('ddd, D MMM YYYY');
}
... using moment.js to format the date, and in the DateEditor ...
$input.datepicker({
showOn: "button",
changeMonth: true,
changeYear: true,
dateFormat: 'd/m/yy',
buttonImageOnly: true,
buttonImage: "../images/calendar.gif"
});
Also you could just localise
You can write formatter for row (i use moment.js too):
function dateTimeFormatter (row, cell, value, columnDef, dataContext) {
var dateTime = Date.parse(value);
var result = moment(dateTime);
return result.format('DD.MM.YYYY hh:mm:ss');
}
First, add code to the slick.formatters.js file in your local library:
Add the custom date formatter in two spots:
$.extend(true, window, {
"Slick": {
"Formatters": {
"PercentComplete": PercentCompleteFormatter,
"PercentCompleteBar": PercentCompleteBarFormatter,
"YesNo": YesNoFormatter,
"Checkmark": CheckmarkFormatter,
"Checkbox": CheckboxFormatter,
"Date": Dateformatter //<< this one
}
}
});
and on the end of the file:
function Dateformatter(row, cell, value, columndef, datacontext) {
if (value === null) {
return "";
} else {
var d = new Date(value);
var m = d.getMonth() + 1;
return (d.getDate() + "/" + m + "/" + d.getFullYear());
}
}
})(jQuery); //<< this line is already present
Now you can add the date formatter in your column definitions:
{
id: "lastLoginDate", name: "LastLoginDate", field: "lastLoginDate", formatter: Slick.Formatters.Date
},

jqGrid Set Selected Rows

I have a jqgrid with multiselect true and I want to set some of rows.(I know the row ids.) How can I do that?
I mean opposite of
$("#myTable").jqGrid('getGridParam', 'selarrrow');
as like:
$("#myTable").jqGrid('setGridParam', 'selarrrow', rowArray);
You have to loop through the rowArray array and call setSelection method for every rowid from the rowArray:
var i, count, $grid = $("#myTable");
for (i = 0, count = rowArray.length; i < count; i += 1) {
$grid.jqGrid('setSelection', rowArray[i], false);
}
$.each(rowsToSelect, function(_, rowId) {
$grid.setSelection(rowId, false);
});
No much difference. Just seemed neater :)
(Pretty amazing that even now, in 2014, jqGrid doesn't persist checkboxes when paging..)
Here's the code I needed to use, with jqGrid 4.4.5, to get the checkboxes to set, after moving to a new page:
var idsOfSelectedRows = []; // list of RowIDs for rows which have been ticked
$("#tblContracts").jqGrid({
...
colModel: [
{ name: 'AddContract', width: 50, align: "center", editable: true, edittype: 'checkbox', editoptions: { value: "True:False" }, formatter: "checkbox", formatoptions: { disabled: false } },
{ name: "ContractName", search: true, width: 80, align: "center" }
],
loadComplete: function () {
for (i = 0; i < idsOfSelectedRows.length; i++) {
$(this).setCell(idsOfSelectedRows[i], 'AddContract', true);
}
},
During development, I put an "alert" in that "for" loop. I found that using "setSelection" simply stepped through my list of RowIDs, selected the row (so it would become highlighted), then moved on to the next, selecting that one instead.
It didn't ever tick any of the checkboxes.
Notice that my "setCell" function includes the name of the jqGrid column where I have a checkbox.
If you cut'n'paste this code, make sure you change this line to reflect the name of your jqGrid checkbox column.

jqgrid get values from combobox inside cell

I'm using select type inside a column , when I'm generating the xml from the grid's data , i can't get the value of the select type cell.
This is my code:
{name:'code',index:'code', width:80, sorttype:"int" , editable:true,edittype:"select",
editoptions:
{
value:"1:11 ;2:22" }
and the xml generating is with:
var dataFromGrid = grid.jqGrid ('getRowData');
var xml = xmlJsonClass.json2xml ({Row: dataFromGrid}, '\t');
I get inside the xml "11" intead of "1".
How can i get the option value?
Thank's In Advance.
I had to do this in local processing mode:
var rows = jQuery(this).getRowData();
var cols = jQuery(this).jqGrid('getGridParam', 'colModel');
for (var col in cols) {
if (cols[col].edittype == 'select') {
var VALs = cols[col].editoptions.value;
if (typeof (VALs) == "object") {
for (var row in rows) {
for (var v in VALs) {
if (rows[row][cols[col].name] == VALs[v]) {
rows[row][cols[col].name] = v;
break;
}
}
}
}
}
}
If you use datatype:"xmlstring" it will be changed to the "local" datatype after the filling of the grid. So like in case of the datatype:"local" the grid has internal data parameter which represent grid data and not the visualization of the current page of data which you receive with
var dataFromGrid = grid.jqGrid ('getRowData');
So I recommend you to use
var dataFromGrid = grid.jqGrid ('getGridParam', 'data');
to get the data from the grid.
if you only need the selected ID in the data, you can specify formatter: 'select'
...
{
name: 'unit', index: 'unit', editable: true, formatter: 'select', edittype: 'select', editrules: { required: true }, editoptions: { value: "1:11 ; 2:22" }
},
...
then retriving the grid data :
var griddata = $('#gridID').getGridParam('data');
alert(JSON.stringify(griddata));

Add multiple input elements in a custom edit type field

Is there a way to create a custom field that has multiple input elements? I'm consulting the documentation and creating a single input element is pretty straight forward, but I'm not exactly sure how you'd add more than one.
Has anyone crossed this bridge before? If so, how did you do it?
Here's some sample code:
...
{name: 'Dimensions', index: 'Dimensions', hidden: true, editable: true,
edittype: 'custom', editoptions: {custom_element: dimensionsElement,
custom_value: dimensionsValue}, editrules: {edithidden: true}},
...
function dimensionsElement(value, options) {
var el = document.createElement("input");
el.type = "text";
el.value = value;
return el;
}
function dimensionsValue(elem) {
return $(elem).val();
}
You can use jQuery to create multiple input elements. So if your field is for example a persons full name you can use following
{ name: 'FullName', editable: true, edittype: 'custom', width: 300,
editoptions: {
custom_element: function(value, options) {
// split full name to the first and last name
var parts = value.split(' ');
// create a string with subelements
var elemStr = '<div><input id="'+options.id +
'_first" size="10" value="' + parts[0] +
'" /></br><input id="'+options.id + '_last' +
'"size="20" value="' + parts[1] + '" /></div>';
// return DOM element from jQuery object
return $(elemStr)[0];
},
custom_value: function(elem) {
var inputs = $("input", $(elem)[0]);
var first = inputs[0].value;
var last = inputs[1].value;
return first + ' '+ last;
}
}},
It is of cause a raw code fragment and you should improve the layout of input elements (the value of size attribute for example). It shows the main concept of building of custom edit elements.
UPDATED: If you use custom editing it is important to use recreateForm: true parameter (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:form_editing). See jqgrid - Set the custom_value of edittype: 'custom' for details.

Resources