1
votes

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

1 Answers

3
votes

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.
      }