在MVC 4中使用Knockout进行远程验证,允许无效数据保存

时间:2016-04-12 13:26:08

标签: asp.net-mvc validation knockout.js knockout-validation remote-validation

您好我在那里使用带有淘汰验证规则的远程验证来检查客户是否与建议日期同时预订。我终于让viewmodel将数据发送到控制器验证方法,并且该方法确实返回true或false但是我开始注意到如果客户端无效,则回调并没有阻止用户保存。

我发现这是通过交换条件并允许控制器方法返回false我调试了客户端并发现回调变量实际上是假的但我没有收到错误消息也没有阻止m保存预约。

我的问题是我错过了一段允许这样的代码,或者是否有我错过的错误?

Viewmodel规则验证:

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})
};

1 个答案:

答案 0 :(得分:1)

根据https://github.com/Knockout-Contrib/Knockout-Validation/wiki/Async-Rules中的定义,只要放一个json即可,就像:

callback(
{ 
    isValid: true //true or false with json format returned from the validation method in your controller, 
    message: "your cusotm error message here" 
}
);