简体   繁体   中英

Knockout.js validation

I'm new to Knockout.js tech where I Googled many site to resolve my situation where I couldn't find a better option. How to validate a date using Knockout.js? Where in my case if the user typed the date in a wrong format say for eg if the valid date format is dd-M-yyyy but the user is typing M-dd-yyyy it should automatically convert it to a valid date format.

My sample code is this,

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
           }

My HTML design is this,

    <input class="form-control" id="dateOfBirth" autocomplete="off" placeholder="Date of Birth" type="text" data-bind="value: dateOfBirth, format:'dd-M-YYYY', valueUpdate: 'afterkeydown'">

Take a look at "Writable computed observables" example 3 and example 4 on the official Knockout documentation site.

Example:

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

Also consider using the textInput binding, instead of value combined with valueUpdate , for consistent cross-browser handling.

Consider using Knockout event and capture its change event and then use moment.js library to convert it into any date format you like.

In HTML:

<input class="form-control" id="dateOfBirth" autocomplete="off" placeholder="Date of Birth" type="text" data-bind="value: dateOfBirth, event: { change: dataChanged}, valueUpdate: 'afterkeydown'">

In javascript: Inside your viewModel

//this function will be called when the date will be changed

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

for further details check moment.js liberary

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