Knockout validation

后端 未结 3 793
不思量自难忘°
不思量自难忘° 2020-12-02 13:03

I have asp.net mvc3 project where I do a bulk edit on a table with knockout binding. I want to do validations like required and number validations while saving data. Is ther

3条回答
  •  悲哀的现实
    2020-12-02 13:38

    If you don't want to use the KnockoutValidation library you can write your own. Here's an example for a Mandatory field.

    Add a javascript class with all you KO extensions or extenders, and add the following:

    ko.extenders.required = function (target, overrideMessage) {
        //add some sub-observables to our observable
        target.hasError = ko.observable();
        target.validationMessage = ko.observable();
    
        //define a function to do validation
        function validate(newValue) {
        target.hasError(newValue ? false : true);
        target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
        }
    
        //initial validation
        validate(target());
    
        //validate whenever the value changes
        target.subscribe(validate);
    
        //return the original observable
        return target;
    };
    

    Then in your viewModel extend you observable by:

    self.dateOfPayment: ko.observable().extend({ required: "" }),
    

    There are a number of examples online for this style of validation.

提交回复
热议问题