简体   繁体   中英

Knockout JS Validation not working

I am a newbie in Knockout JS. i want to apply validations in KO. i have used plugin knockout.validation.min.js . I have implemented it like this but not working

My View Model

 $(document).ready(function myfunction() {

        ko.applyBindings(new EmployeeKoViewModel());

    })
    var EmployeeKoViewModel = function () {
    var self = this;
        self.EmpId = ko.observable()
        self.Name = ko.observable("").extend({ required: { message: "please enter employee name " } });
        self.City = ko.observable("").extend({ required: { message: "please enter employee city " } });
        self.Employees = ko.observableArray();


             //GetEmployees();
            var EmpData = {
                EmpId: self.EmpId,
                Name: self.Name,
                City: self.City,

            };
            function GetEmployees() {
                $.ajax({
                    type: "GET",
                    url: "/Employee/About",
                }).done(function (data) {

                    self.Employees(data);
                }).error(function (ex) {
                    alert("Error");
                });
            }
        self.save = function () {
            var EmployeeKoViewModel.errors = ko.validation.group(self);
            if (!EmployeeKoViewModel.errors().length <= 0) {
                EmployeeKoViewModel.errors.showAllMessages();
                return false;
            }
            $.ajax({
                type: "POST",
                url: "/Employee/Save",
                data: ko.toJSON(EmpData),
                contentType: "application/json",
                success: function (data) {
                    self.EmpId(data.EmpId);
                    GetEmployees();

                },
                error: function () {
                    alert("Failed");
                }
            });
            //Ends Here
        };
}

I have created a fiddle it is working when i comment GetEmployees() method but not working with it

At this line

var EmployeeKoViewModel.errors = ko.validation.group(self);

you are trying to create a variable, but the syntax is like creating an object with a property which is of course invalid. In order to fix this you can initialize your object first:

var EmployeeKoViewModel = {};
EmployeeKoViewModel.errors = ko.validation.group(self);
if (!EmployeeKoViewModel.errors().length <= 0) {
    EmployeeKoViewModel.errors.showAllMessages();
    return false;
}

Here is a working jsFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM