Knockout validation
Asked Answered
H

3

48

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.

Hardee answered 25/1, 2012 at 0:39 Comment(0)
S
86

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.' }
    })
};
Skinned answered 5/3, 2012 at 16:47 Comment(7)
Is it me or is the fiddle broken on IE9 and IE10? Works on Chrome and Firefox tho'.Sonni
@rob: IE9 gives me a; "script was blocked due to mime type mismatch"-error. Probably you can disable this security check.Skinned
@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/1369Skinned
Thanks Cohen. So NOW I'll have confidence it'll work on my site even if it's ugly on jsfiddle. :-)Sonni
Here's a working version of the original fiddle from eric barnard that isn't as ugly. :) jsfiddle.net/alexdresko/KHFn8/2403Beasley
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).Echevarria
Knockout Validation is now hereBerwick
P
6

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.

Pharisee answered 12/5, 2015 at 10:1 Comment(1)
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 timeInvulnerable
A
-24

Knockout.js validation is handy but it is not robust. You always have to create server side validation replica. In your case (as you use knockout.js) you are sending JSON data to server and back asynchronously, so you can make user think that he sees client side validation, but in fact it would be asynchronous server side validation.

Take a look at example here upida.cloudapp.net:8080/org.upida.example.knockout/order/create?clientId=1 This is a "Create Order" link. Try to click "save", and play with products. This example is done using upida library (there are spring mvc version and asp.net mvc of this library) from codeplex.

Airglow answered 30/8, 2013 at 0:4 Comment(3)
-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.Taking
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 frameworkMulatto
@SeanThorburn Agreed. I didn't even think it was that bad of an answer. I could see this working fairly well in some scenarios.Kowalewski

© 2022 - 2024 — McMap. All rights reserved.