Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map view models to KnockoutJS Validation

I've been building out a page using ASP.NET MVC 2 using KnockoutJS, KnockoutJS Mapping plugin,, and jQuery 1.7.1. I'd like to be able to also use the KnockoutJS Validation plugin (found here). However I need to have both server and client side validation happening.

Is it possible to have my view models map to the KnockoutJS Validation plugin which uses the .extend() method?

EDIT: Example. Automatically turn this:

[Required]
public string Firstname { get; set; }

Into this:

var viewmodel = {
    firstname: ko.observable().extend({ required: true });
}
like image 591
Ryan Avatar asked Feb 16 '12 01:02

Ryan


People also ask

What is knockout mapping?

Knockout is designed to allow you to use arbitrary JavaScript objects as view models. As long as some of your view model's properties are observables, you can use KO to bind to them to your UI, and the UI will be updated automatically whenever the observable properties change.

How does KnockoutJS work?

KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites. The model separates the application's Model (stored data), View (UI) and View Model (JavaScript Representation of model).

How do I assign a value to knockout observable?

To create an observable, assign the ko. observable function to the variable. A default value can be specified in the constructor of the call. Knockout then converts your variable into a function and tracks when the value changes, in order to notify the UI elements associated with the variable.

What is Ko applyBindings?

To apply bindings for the whole HTML document, it can be done using the Knockout function applyBindings() with passing the view model as the first and the only parameter: ko. applyBindings(viewModel); To apply Knockout for a part of the HTML document, pass the DOM element as a second parameter: ko.


3 Answers

In the Mvc Controls Toolkit I implemented an engine that enables the usual Mvc validation (data annotations or whatever) on knockout.js.Both client side and server side validation can be enabled. Moreover, knockout can be used with Mvc helpers, some bindings are inferred automatically, etc.

like image 166
Francesco Abbruzzese Avatar answered Oct 09 '22 08:10

Francesco Abbruzzese


If you are using knockoutjs and jquery, I came up with the following very simple method for doing basic client side validation.

Wherever you want to display the error message on your page, include a span tag like this:

<span name="validationError" style="color:Red" 
data-bind="visible: yourValidationFunction(FieldNameToValidate())">
* Required.
</span>

Obviously you need to write "yourValidationFunction" to do whatever you want it to do. It just needs to return true or false, true means display the error.

You can use jquery to prevent a user from proceeding if any validations errors are displayed. You probably already have a save button that triggers a javascript function to do some ajax or whatever, so just include this at the top of it:

 if ($("[name='validationError']:visible").length > 0) {
        alert('Please correct all errors before continuing.');
        return;
    }

This is a lot simpler and more flexible than many other validation solutions out there. You can position your error message wherever you want, and you don't need to learn how to use some validation library, and this method works regardless of server side technology.

like image 35
pilavdzice Avatar answered Oct 09 '22 08:10

pilavdzice


I'd recommend using the built in MVC clientside validation, you might need to invoke it, try this:

$.validator.unobtrusive.parse(yourFormElement)

Code from: https://stackoverflow.com/a/5669575/941536

Not sure if MVC2 has unobtrusive clientside validation though, unsure if an upgrade to MVC3 would be an option for you if necessary.

like image 38
kendaleiv Avatar answered Oct 09 '22 07:10

kendaleiv