Knockout date validation not working correctly

冷暖自知 提交于 2019-12-02 04:03:21

A little late by why not... The date rule does seem a bit too permissive for my uses as well. If you like moment but want something cleaner for the caller, add your rule to the validation.rules object:

ko.validation.rules['simpleDate'] = {
    validator: function (val, validate) {
        return ko.validation.utils.isEmptyVal(val) || moment(val, 'MM/DD/YYYY').isValid();
    },
    message: 'Invalid date'
};

And then use it like:

var someDate= ko.observable().extend({ simpleDate: true });

Very late for this, but just want to share my updates on @ChoptimusPrime's answer. Not hard-coding the format:

ko.validation.rules['dateAndFormat'] = {
    validator: function (val, format) {
        return ko.validation.utils.isEmptyVal(val) || moment(val, format).isValid();
    },
    message: 'Please provide a valid date.'
};
ko.validation.registerExtenders();

The only working solution I have for now is below. The problem with this validator is that it also validates default(EN) date format as valid, so I have to add a IF to return this as invalid date format.

var dateValidator = function (val) {
            if (!val)
                return false;
            if (moment(val, 'DD.MM.YYYY HH:mm').isValid()) {
                return true;
            }
            else
                return false;
        };

var startDate = ko.observable().extend({ validation: { validator: dateValidator, message: 'Start of task is not in correct format.' } });

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!