我是Knockout.js技术的新手,我用谷歌搜索了很多网站来解决我找不到更好选择的情况。如何使用Knockout.js验证日期?在我的例子中,如果用户以错误的格式输入日期,例如,如果有效的日期格式是dd-M-yyyy,但用户输入的是M-dd-yyyy,则应该自动将其转换为有效的日期格式。
我的示例代码是这样的:
self.dateOfBirth = ko.observable(0).extend({
required: { message: 'Date of Birth is required', params: true },
date: { format: 'dd-M-YYYY' ,
message: 'Not a valid date format',params:true
}我的HTML设计是这样的,
<input class="form-control" id="dateOfBirth" autocomplete="off" placeholder="Date of Birth" type="text" data-bind="value: dateOfBirth, format:'dd-M-YYYY', valueUpdate: 'afterkeydown'">发布于 2015-04-10 19:25:59
看看官方Knockout文档站点上的"Writable computed observables“example 3和example 4。
示例:
this.formattedDate = ko.pureComputed({
read: function () {
return this.date();
},
write: function (value) {
// convert date to dd-M-YYYY, then write the
// raw data back to the underlying "date" observable
value = convertDate(value); // add your own conversion routine
this.date(value); // write to underlying storage
},
owner: this
});还要考虑使用textInput绑定,而不是将value与valueUpdate结合使用,以实现一致的跨浏览器处理。
发布于 2018-11-14 04:15:37
考虑使用Knockout事件并捕获其更改事件,然后使用moment.js库将其转换为您喜欢的任何日期格式。
在HTML中:
<input class="form-control" id="dateOfBirth" autocomplete="off" placeholder="Date of Birth" type="text" data-bind="value: dateOfBirth, event: { change: dataChanged}, valueUpdate: 'afterkeydown'">
在javascript中:在viewModel中
//日期变更时会调用该函数
self.dataChanged = function(){ //using moment .js here change the format to dd-M-YYYY as desired var validFormat = moment(self.dateOfBirth()).format('dd-M-yyyy'); self.dateOfBirth(validFormat); }
有关更多详细信息,请查看moment.js图书馆
https://stackoverflow.com/questions/29559143
复制相似问题