how to? with knockout js validations - validation

I've started using knockout js validations with http://ericmbarnard.github.com/Knockout-Validation/ validation engine, and I'm not clear as to how to do the following:
1) Say I want to set a particular field required based on a condition. How do I do that?
e.g.
this.Username = ko.observable().extend({ required: true }); // make required = true only if this.UserType = 2, etc...
2) I've got the validation messages firing right next to the field being validated. I want only an '*' to appear next to the field and display the error messages in a validationsummary field at the bottom of the page. All validation errors should display there. How to do that?
3) The form submit to be avoided until the form validation is passed. Rightnow, I get the validation error messages, still the form gets submitted. So I guess I'm doing something wrong. Following is my code:
$(document).ready(function () {
var model;
// enable validation
ko.validation.init();
$.ajax({
type: "POST",
url: SERVER_PATH + '/jqueryservice/DataAccessService.asmx/GetData',
async: false,
data: "{ }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result, status) {
model = new ViewModel(result);
ko.applyBindings(model);
},
error: GetDataError
});
$('#submit').click(function () {
var data = ko.toJS(model);
delete data.Vehicles;
delete data.CopyWeeks;
delete data.SetupTotal;
delete data.CloseTotal;
var mappedItems = ko.utils.arrayMap(data.DailyItemList, function (item) {
delete item.Add;
delete item.Delete;
return item;
});
data.DailyItemList = mappedItems;
$.ajax({
type: "POST",
url: SERVER_PATH + '/jqueryservice/DataAccessService.asmx/ProcessData',
async: false,
data: ko.toJSON(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result, stat) {
alert(success);
return false;
},
error: function (e) {
alert(e);
}
});
});
});
Thanks in advance for your help.
EDIT:
I've seen that I can set the validation configuration as follows:
ko.validation.configure({
decorateElement : false,
errorMessageClass: 'errorMsg',
insertMessages : false,
parseInputAttributes : true,
messageTemplate: 'sErrorMsg'
});
ko.validation.init();
but I'm not sure how I can define my error message template 'sErrorMsg'

1). Say I want to set a particular field required based on a condition....
For this ko validation contains a native rule. You can do something like :
var myObj = ko.observable().extend({ required: {
onlyIf: function() {
//here you can place your codition and can return..
//true or false accordingly
}
}});
2). I've got the validation messages firing right next to the field being validated..
For this you should check Validation Binding. In this validationOptions can do the job for you.
Update: here's a fiddle which demonstrate the use of messageTemplate binding as per your requirement.
http://jsbin.com/ocizes/3/edit
3). The form submit to be avoided until the form validation is passed....
For this you can use use group , like :
yourViewModel.Errors = ko.validation.group(yourViewModel);
Now the Errors property contains the error messages of your observables, if any. So before submitting the form you can put check something like :
if(yourViewModel.Errors().length == 0) {
//submit the form
}
else {
yourViewModel.Errors.showAllMessages();
//this line shows all the errors if validation fails,
//but you can omit this.
}

Related

Kendo Tooltip is empty

dI use a kendo tooltip on cells of a column of a kendo grid but the content of the tooltip is empty.
When I use the chrome debugger, values are correctly set but there is nothing in my tooltip.
$("#gri").kendoTooltip({
filter: "span.tooltip",
position: "right",
content: function (e) {
var tooltipHtml;
$.ajax({
url: ".." + appBaseUrl + "api/Infobulle?id=" + $(e.target[0]).attr("id"),
contentType: "application/json",
dataType: "json",
data: {},
type: "GET",
async: false
}).done(function (data) { // data.Result is a JSON object from the server with details for the row
if (!data.HasErrors) {
var result = data.Data;
tooltipHtml = "Identifiant : " + result.identifiant;
} else {
tooltipHtml = "Une erreur est survenue";
}
// set tooltip content here (done callback of the ajax req)
e.sender.content.html(tooltipHtml);
});
}
Any idea ? Why it is empty ?
After looking at the dev's answer on telerik forums, i found out that you need to do something like
content: function(){
var result = "";
$.ajax({url: "https://jsonplaceholder.typicode.com/todos/1", async:false , success: function(response){
result = response.title
}});
return result;
}
changing directly with e.sender.content.html() won't work, instead we have to return the value. And i tried several approach :
i tried mimick ajax call with setTimeOut, returning string inside it or using e.sender.content.html() wont work
i tried to use content.url ( the only minus i still don't know how to modify the response, i display the whole response)
the third one i tried to use the dev's answer from here
AND check my example in dojo for working example, hover over the third try

Populating a kendo multiselect with ajax data

I am using a kendo multiselect widget for users to select different values pulled from the database via an ajax call. The ajax call takes one parameter, searchValue, which will narrow down the returned data. Here is my controller:
[HttpPost]
public JsonResult ProfitabilitySearch(string searchValue)
{
return Json(InventoryDataAccess.ProfitabilitySearch(searchValue));
}
1) How do you get the value from the text box to use as your searchValue? I commented the area in question below.
Here is my dataSource:
var searchDataSource = new kendo.data.DataSource({
transport: {
read: function () {
$.ajax({
type: 'POST',
url: Firm.ProfitabilitySearchURL,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
//'SuperClient' is test data to see if it works, but what do i
//need to make searchValue = what I type?
data: JSON.stringify({ searchValue: 'SuperClient'}),
success: function (data) {
return data.RESULT;
}
});
}
},
group: { field: 'category' },
serverFiltering: true
});
And here is where I create the multiselect widget:
var TKSearch = $("#TKSearch").kendoMultiSelect({
dataSource: searchDataSource,
autoBind: false,
minLength: 3,
placeholder: 'Search Timekeepers...',
dataTextField: 'label',
dataTextValue: 'value',
delay: 200
}).data("kendoMultiSelect");
I'm not sure if this will help, but here is the structure of the json that is returned from the ajax call:
{"label":"SUNFLOWER REALTY CORP. (023932)","value":"023932","category":"RC"}
Solving the first question above may answer my second question so I will wait to ask that until after.
You can use functions for the request parameters.
var searchDataSource = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: 'POST',
url: Firm.ProfitabilitySearchURL,
contentType: 'application/json; charset=utf-8',
data: {
searchValue: function () {
// better: use a model property instead of this
return $("#TKSearch").data('kendoMaskedTextBox').value();
}
},
success: function (data) {
options.success(data.RESULT);
}
});
}
},
group: { field: 'category' },
serverFiltering: true
});
Notes
This really should be a GET request. Use POST for requests that actually change data on the server and GET for requests that merely retrieve data from the server.
You do not have to JSON.stringify() yourself. jQuery does that transparently.
Specifying dataType is completely superfluous, jQuery will figure this out from the response headers.
Reading the input value via jQuery is not clean. Use the data-bound model property instead.
The callback invocation (options.success())
This sample lacks HTTP error handling, you must add that.

How to retrieve CheckBox value in Controller - Asp.Net MVC 3 and Jquery

Problem: Check box value display null in controller.cs. but it is working perfectly according to selection of row from jqgrid. But when I select any row and update all the field it will pass to the controller with modified value but only IsEnabled field comes null.
I have Database Field called IsEnabled which has Bit data type.
I have written following code in .cshtml
<input type="checkbox" value='Yes' offval='No' name="IsEnabled" />
I am using following code to bind check box value as per in database
grid.jqGrid('GridToForm', gsr, "#order");
I have save button. When I click on save following code will execute
$("#btnSave").click(function () {
var data = JSON.stringify($('#order').serializeObject());
var href = '#Url.Action("SaveData", "Users")';
var ajaxResponse = $.ajax({
type: "post",
url: href,
dataType: 'json',
data: data,
contentType: "application/json; charset=utf-8",
success: function (result) {
if (result.Success == true) {
alert("Success");
}
else {
alert("Error: " + result.Message);
}
}
});
Following code written in Controller.cs
(in FormValue it will show all the updated value correctly except IsEnabled, it will display always null.)
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveData(User FormValue)
{
string message = "";
return Content(message);
}
You must delete this code ( if use jquery ajax )
[AcceptVerbs(HttpVerbs.Post)]
when you use post back and send class use above code
send class with jQuery use this code:
try it:
$.ajax({
type: "post",
url: href,
dataType: 'json',
data: SON.stringify({ FormValue : { ID : $('#controlIdName').val() , Name : $('#ControlName').val() } }),
contentType: "application/json; charset=utf-8",
success: function (result) {
if (result.Success == true) {
alert("Success");
}
else {
alert("Error: " + result.Message);
}
}

Wrong to use AJAX?

I have a view(MVC3) that users place orders from. The view is bound to a model that i use to display modelitems from. There are two functionalities on this view. First you enter the customers details and then you choose the items the user has ordered. This is the code i´m using to build another model to be sent back to serverside:
var modelItems = {
ModelID: [],
Amount: []
};
var serviceModel = {
Name: $.trim($('#name').val()),
Customernumber: $.trim($('#customernumber').val()),
Address1: $.trim($('#address1').val()),
Address2: $.trim($('#address2').val()),
Zipcode: $.trim($('#zipcode').val()),
City: $.trim($('#city').val()),
Country: $.trim($('#country').val()),
Phone: $.trim($('#phone').val()),
Mobile: $.trim($('#mobile').val()),
Email: $.trim($('#email').val())
};
$('div.modelSpan').each(function (i) {
var textBox = $(this).children();
var value = $(textBox).val();
if (value != '0' && value != '') {
var modelID = $(textBox).attr('name');
modelItems.ModelID.push(modelID);
modelItems.Amount.push(value);
}
});
var accessory = {
ModelItems: modelItems,
ServiceModel: serviceModel
};
$.ajax({
url: '/Site/Order', //Renamed sec reasons
type: "POST",
data: JSON.stringify(accessory),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (ordernumber) {
window.location.href = "/Site/OrderInfo/" + businessAB + "/" + ordernumber;
},
error: function () {
alert('error');
}
});
Cool thing in MVC3 is that my accessory automatically binds to my model on serverside called AccessoriesModel. On callback success i´m setting new href to a receipt site to show user what has been created. This all works but my issue is that i would like the receipt view(OrderInfo) to be returned from my controller that receives the [httppost] and not setting new href. Is there a way to do this? This is easy when using regular form submit but because the values for my model dont come from one form it complicates things. Maybe I shouldn´t use AJAX?
You could use knockout JS with Ajax and render your pages with a mixture of JavaScript objects and regular html.

jquery validation always fails

Why is the following validation function always failing. It even fails if I have both return case with true.
$.validator.addMethod("validate_old_password", function(value, element){
$.ajax({
url: '/users/ajaxPage_password_validation/',
type: 'POST',
dataType: 'text',
debug: true,
data: {
password: $("#id_old_password").val()
},
success: function(response){
if (response == "True") {
console.log('aa')
return true;
}// correct PW
return false; // bad PW
}
})
}, "password not valid");
I believe its because of the deferred execution.
When the "validate_old_password" method is called it simply kicks off the ajax call and continues to the end of the method, it won't wait around for the response.
You may want to consider using the remote validation options in the validation plugin.

Resources