Knockout validation

104,211

Solution 1

Have a look at Knockout-Validation which cleanly setups and uses what's described in the knockout documentation. Under: Live Example 1: Forcing input to be numeric

You can see it live in Fiddle

UPDATE: the fiddle has been updated to use the latest KO 2.0.3 and ko.validation 1.0.2 using the cloudfare CDN urls

To setup ko.validation:

ko.validation.rules.pattern.message = 'Invalid.';

ko.validation.configure({
    registerExtenders: true,
    messagesOnModified: true,
    insertMessages: true,
    parseInputAttributes: true,
    messageTemplate: null
});

To setup validation rules, use extenders. For instance:

var viewModel = {
    firstName: ko.observable().extend({ minLength: 2, maxLength: 10 }),
    lastName: ko.observable().extend({ required: true }),
    emailAddress: ko.observable().extend({  // custom message
        required: { message: 'Please supply your email address.' }
    })
};

Solution 2

If you don't want to use the KnockoutValidation library you can write your own. Here's an example for a Mandatory field.

Add a javascript class with all you KO extensions or extenders, and add the following:

ko.extenders.required = function (target, overrideMessage) {
    //add some sub-observables to our observable
    target.hasError = ko.observable();
    target.validationMessage = ko.observable();

    //define a function to do validation
    function validate(newValue) {
    target.hasError(newValue ? false : true);
    target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
    }

    //initial validation
    validate(target());

    //validate whenever the value changes
    target.subscribe(validate);

    //return the original observable
    return target;
};

Then in your viewModel extend you observable by:

self.dateOfPayment: ko.observable().extend({ required: "" }),

There are a number of examples online for this style of validation.

Share:
104,211

Related videos on Youtube

Kurkula
Author by

Kurkula

Updated on March 01, 2020

Comments

  • Kurkula
    Kurkula over 4 years

    I have asp.net mvc3 project where I do a bulk edit on a table with knockout binding. I want to do validations like required and number validations while saving data. Is there any easier way to do knock out validations. PS: I am not using forms.

  • Rob Koch
    Rob Koch over 11 years
    Is it me or is the fiddle broken on IE9 and IE10? Works on Chrome and Firefox tho'.
  • Cohen
    Cohen over 11 years
    @rob: IE9 gives me a; "script was blocked due to mime type mismatch"-error. Probably you can disable this security check.
  • Cohen
    Cohen over 11 years
    @rob: To make it working in IE, I've removed the resources and copied the knockout.validation into the fiddle (ugly, I know), it does work however: jsfiddle.net/KHFn8/1369
  • Rob Koch
    Rob Koch over 11 years
    Thanks Cohen. So NOW I'll have confidence it'll work on my site even if it's ugly on jsfiddle. :-)
  • Alex Dresko
    Alex Dresko over 11 years
    Here's a working version of the original fiddle from eric barnard that isn't as ugly. :) jsfiddle.net/alexdresko/KHFn8/2403
  • Overflew
    Overflew almost 11 years
    The JS Fiddles link to the Knockout files via GitHub - and the old versions are no longer hosted. (Many linked examples reference v2.1, and it's now on v2.2 . They also no longer host a knockout-latest.js).
  • Mike
    Mike about 10 years
    -1 This is not peculiar to Knockout. ALL JavaScript needs to ALWAYS be validated on the server as well. The Knockout Validation library validates client side.
  • DropHit
    DropHit almost 10 years
    Adding extra cycles to ping the server side validation i think is not useful unless necessary when in fact you can validate client side first :) then ensure via server-side. This is the fact whether you use KO or any other framework
  • crissdev
    crissdev over 9 years
    Knockout Validation is now here
  • MPavlak
    MPavlak about 8 years
    @SeanThorburn Agreed. I didn't even think it was that bad of an answer. I could see this working fairly well in some scenarios.
  • Clarence
    Clarence almost 7 years
    ok, but I'm getting my viewmodel from server side via ajax and mvc razor and knockout.mapping. I also import into javaScript modules direct from serverside using .net mvc, newton json conversions, and htlml raw helpers... Now.... how can I extend my observables without applying observing one field at a time