Knockout Validation Plugin Custom Error Message - knockout-validation

Based on the following, how exactly do I setup the callback to display a custom error message instead of the default message?
ko.validation.rules['exampleAsync'] = {
async: true, // the flag that says "Hey I'm Async!"
validator: function (val, otherVal, callBack) { // yes, you get a 'callback'
/* some logic here */
// hand my result back to the callback
callback( /* true or false */ );
// or if you want to specify a specific message
callback( /* { isValid: true, message: "Lorem Ipsum" } */ );
},
message: 'My default invalid message'
};

ko.validation.rules['exampleAsync'] = {
async: true,
validator: function (val, otherVal, callBack) {
// make an ajax call or something here to do your async validation
$.ajax({ type: 'post', url: 'some url', data: val, success: function (data) {
if (data.success) {
callback({ isValid: true, message: "yay it worked"});
} else {
callback({ isValid: false, message: data.message });
}
});
},
message: 'My default invalid message'
};

Related

Errors occur submit batch request

I am trying to use batch request for sending http post to the server.
The code snippet, which generate the request:
_.each(aNewDates, function (oNew) {
oModel.create("/CostCenterCalendarSet", oNew, {
groupId: "newDates"
});
});
oModel.setDeferredGroups(["newDates"]);
and the submit method:
oModel.submitChanges({
groupId: "newDates",
oSuccess: function (oMsg) {
return observer.next(oMsg);
},
oError: function (oErr) {
return observer.error(oErr);
},
});
as response I've got following error:
What am I doing wrong?
Update
I tried with ODataModel read method and does not get any result.
let oPlantFilter = new sap.ui.model.Filter("Plant", sap.ui.model.FilterOperator.EQ, oSelectedData.sPlant);
let oWcFilter = new sap.ui.model.Filter("WorkCenter", sap.ui.model.FilterOperator.EQ, oSelectedData.sWc);
oModel.read("/CostCenterCalendarSet", {
groupId: "query-dates",
filters: [oPlantFilter, oWcFilter]
});
oModel.setDeferredGroups(["query-dates"]);
return Rx.Observable.create(function (subscriber) {
oModel.submitChanges({
groupId: "query-dates",
success: function (oData, oResponse) {
return subscriber.next(oResponse);
},
error: function (oErr) {
return subscriber.error(oErr);
},
});
});

Refreshing data in ui-grid

In my screen I have a ui-grid that need be load when the user click in button "search".
I'm making this:
// Ajax call
$("#btn-Pesquisar").click(function () {
var form = $('#frm-Pesquisar-Acos-Internos');
$.ajax({
cache: false,
async: true,
type: "POST",
url: form.attr('action'),
dataType: "json",
data: form.serialize(),
success: function (result) {
angular.element(document.getElementById('grd-Resultado')).scope().atualizarRegistros(JSON.parse(result));
$('#divResultadoPesquisa').show();
}
});
});
When the call ocurred with success, I call a function called "atualizarRegistros"
$scope.atualizarRegistros = function (result) {
$scope.grdResultado.data = result;
}
This is a definition from my grid:
$scope.grdResultado = {
showGridFooter: true,
enableSorting: true,
enableFiltering: true,
enableColumnResizing: true,
enableGridMenu: true,
columnDefs: [
{ name: 'Código', field: 'COD_GRUPO_ACO', minWidth: 48 },
{ name: 'Norma', field: 'COD_IDENT_NORMA', minWidth: 60 }
]
};
the result is:
[{"COD_IDENT_ACO":"C0981","COD_GRUPO_ACO":"C","COD_SUBGR_ACO":"0","COD_GRUPO_SUCAT":"04","COD_GRUPO_CUSTO":"36","COD_IDENT_FMACO":"5XX","NOM_IDENT_ACO":"P595R","COD_SITUA_ACO":"A","IDC_ACO_TRANS":"N","DTH_INCLU_REG":"2005-11-23T12:13:36","COD_IDENT_USUAR":"AC42911","COD_UNMED_PESES":"G/CM3","COD_GRUPO_ENCHA":null,"COD_ACO_MATPR":null,"COD_SERIE_ACO":null,"COD_IDENT_NORMA":"ACE","COD_TIPO_ACO":"P595R","NOM_ABREV_ACO":"595R","VLR_DIAME_IDEAL":null,"VLR_PESO_ESPEC":7.850,"VLR_TEMT1_LINGO":null,"VLR_TEMT2_LINGO":null,"TEX_OBSER_ACO":"Adição
de Ca-Si para globulizar inclusões, processo de desgazeificação no
VOD, projeto Flapper Valve.","VLR_TEMTP_LINGO":null,"DESC_ACO":"P595R
- ACE"}]
But when the method is executed, I get this error:
newRawData.forEach is not a function at Grid.modifyRows
I don't know what i can do now.
Help-me!
I'm not sure but can you check, if the data gets an array.
Greets Christian

Remote Validation with Knockout in MVC 4, Allowing invalid data to save

Hi there I am using remote validation with knockout validation rules to check if a client is booked at the same time as the proposed date. I finally got the viewmodel sending data to the controller validation method and the method does return a true or false however i began to notice that the call back was not stopping the user from saving if the client is not valid.
I found this by swapping the conditions and allowing the controller method to return false I debugged the client side and found that the call back variable was in fact false but i was not receiving an error messae nor was it stopping m from saving the appointment.
My question is am i missing a piece of code that allows this or is there a bug that i am missing?
Viewmodel rule validation:
ko.validation.rules['validateClientasync'] = {
async: true,
message: 'Client is already booked in at this time!',
validator: function (val, parms, callback) {
var defaults = {
url: '/Appointments/CheckClient/',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
success: function (data) {
callback(/* true or false depending on what you get back in data */);
}
};
if (parms.data != undefined && parms.data.appointment != undefined) {
var appointment = ko.toJS(parms.data.appointment);
$.ajax({
url: '/Appointments/CheckClient/',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: ko.toJS(parms.data.appointment),
success: function(data) {
callback(/* true or false depending on what you get back in data */);
}
});
}
}
};
ko.validation.registerExtenders();
self.appointment = {
id: appointment.id,
start: ko.observable(appointment.start),
end: ko.observable(appointment.end),
text: ko.observable(appointment.text),
clientid: ko.observable(appointment.clientid).extend({
validateClientasync: {
data: self
}
}),
employeeid: ko.observable(appointment.employeeid),
roomid: ko.observable(appointment.roomid),
fee: ko.observable(appointment.fee).extend({min: 10})
};
according to the definition in https://github.com/Knockout-Contrib/Knockout-Validation/wiki/Async-Rules, just put a json there would be enough, like:
callback(
{
isValid: true //true or false with json format returned from the validation method in your controller,
message: "your cusotm error message here"
}
);

Delete, No url is set in jqgrid

I'm using jqgrid and when deleting a row in the grid i get the alert "Delete selected record?" and when i click ok i have written a code in onClickSubmit to make a ajax call to the controller which takes some parameters and delete the record. The functionality works fine.
But when i click "Delete" button in the alert i get an error "No url is set". Now, i have a url inside my ajax call which does the function. Why is the error thrown?
jqGrid:
var selectedRowId = "125";
$("#AttachmentsGrid").jqGrid({
url: '#Url.Action("LoadTransactionAttachments", "Home")',
postData: { 'transactionId': selectedRowId },
mtype: 'GET',
datatype: 'json',
jsonReader: {
id: 'AttachmentId',
repeatitems: false
},
height: 'auto',
hidegrid: false,
rownumbers: true,
autowidth: true,
shrinkToFit: false,
rowNum: 10,
pager: '#AttachmentsPager',
caption: "Attachments",
colNames: ['AttachmentName'],
colModel: [{ name: 'AttachmentName', index: 'AttachmentName', formatter: imageFormatter, unformat: imageUnFormatter }],
beforeRequest: function () {
responsive_jqgrid($(".jqGrid"));
},
onSelectRow: function (id) {
var statusId;
attachmentId = id;
var selectValues = jQuery('#AttachmentsGrid').jqGrid('getRowData', id);
attachmentName = selectValues.AttachmentName;
if (accessLevel.HasDeleteAttachmentAccess == true)
$("#del_AttachmentsGrid").show();
else
$("#del_AttachmentsGrid").hide();
},
loadComplete: function () {
UnBlockUI();
}
});
jQuery("#AttachmentsGrid").jqGrid('navGrid', '#AttachmentsPager', {
edit: false, add: false, del: true, search: false, refresh: true, refreshtext: ""
}, {}, {}, {
// url: '#Url.Action("UpdateDummyData", "Home")',
// Delete attachment event.
onclickSubmit: function (response, postData) {
$.ajax({
url: '#Url.Action("DeleteSelectedTransactionAttachment", "Home")',
datatype: 'json',
data: { 'attachmentId': JSON.stringify(postData), 'attachmentName': attachmentName, 'transactionId': selectedRowId },
type: 'POST',
success: OnCompleteDeleteAttachments,
error: function (xhr, status, error) {
if (xhr.statusText == "Session TimeOut/UnAuthorized") {
alert(xhr.statusText);
window.location.href = '#Url.Action("LogOut", "Account")';
}
else
alert(xhr.responseText);
}
});
It works when i give some Dummy url in delete method which i dont need. I need another way to solve this.?
FYI, This happens for me also during the edit of a row using form editing.
It seems to me that you try to use Delete in a wrong way. What you do is making Ajax request to '#Url.Action("DeleteSelectedTransactionAttachment", "Home")' with some additional data, do some unknown additional action inside of OnCompleteDeleteAttachments in case of successful deleting and do additional error handling in case of "Session TimeOut/UnAuthorized" error in statusText.
I think that correct implementation should looks more as the following
jQuery("#AttachmentsGrid").jqGrid('navGrid', '#AttachmentsPager', {
edit: false, add: false, search: false, refreshtext: ""
}, {}, {}, {
url: '#Url.Action("DeleteSelectedTransactionAttachment", "Home")',
serializeDelData: function (postData) {
return {
attachmentId: JSON.stringify(postData),
attachmentName: attachmentName,
transactionId: selectedRowId
}
},
errorTextFormat: function (xhr) {
if (xhr.statusText == "Session TimeOut/UnAuthorized") {
window.location.href = '#Url.Action("LogOut", "Account")';
} else {
return xhr.responseText;
}
},
afterSubmit: OnCompleteDeleteAttachments
});

jqxgrid not displaying busy or loading indicator

I am using jqxgrid and I have below code snippet and i want to display load indicator on button click which calls the Ajax method and hide it on the success method or anyway other to display it as i need to show loading indicator from the time request made till i get the data
$("#btnSearch").bind('click', function () {
//show indicator here
LoadLookUpSearchGrid();
}
//Ajax call to fetch data
function LoadLookUpSearchGrid() {
var filterRows = getGridRows();
$.ajax({
type: 'POST',
dataType: 'json',
async: false,
cache: false,
url: 'AddEditView.aspx/LoadLookUpSearchGrid',
data: JSON.stringify({ FilterType: $('select#ddlFilterType').val() , Id: $("#txtId").val() , Name: $("#txtName").val(), SearchText: '', FilterRows: filterGridRows}),
contentType: 'application/json; charset=utf-8',
success: function (data) {
var source = data.d;
SetSearchFields($('select#ddlFilterType option:selected').text(), source);
},
error: function (err) {
alert(err.text + " : " + err.status);
}
});
};
//source object to format data
function SetSearchFields(fieldName, source) {
var columns;
if (fieldName == "Operating Company") {
source =
{
datatype: "xml",
datafields: [
{ name: 'COMPANY', type: 'string' },
{ name: 'DESCR', type: 'string' }
],
async: false,
root: "Company",
localdata: source
};
columns = [
{ text: 'OPCO ID', dataField: 'COMPANY', width: '30%' },
{ text: 'Company Name', dataField: 'DESCR', width: '65%' }
];
}
lookupSearchResultGrid(source, columns,fieldName);
}
//adaptor to fill source and bind grid
function lookupSearchResultGrid(source, columns,fieldName) {
var searchViewGridDataAdapter = new $.jqx.dataAdapter(source);
$("#divLookupSearch").jqxGrid(
{
width: '100%',
source: searchViewGridDataAdapter,
theme: theme,
sortable: true,
pageable: true,
autoheight: true,
selectionmode: 'checkbox',
columns: columns
});
//hide indicator here on on success method of ajax call
};
On the click of the button call showloadelement and in the Ajax call success callback function call hideloadelement.
$("#btnSearch").bind('click', function () {
$('#divLookupSearch').jqxGrid('showloadelement');
//show indicator here
LoadLookUpSearchGrid();
}
...
success: function (data) {
$('#jqxGrid').jqxGrid('hideloadelement');
var source = data.d;
SetSearchFields($('select#ddlFilterType option:selected').text(), source);
},
...
Best Regards,
Alpesh

Resources