سؤال

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 });
}
هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

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.

The validation plugin works in the way that you extend the observables you want to validate.

It doesn't matter if they are created from mappings, just create a function that you run after the mappning has been done and add all the validation you want.

Or, if you want you can use the validation bindings. Read the Readme on Github for knockout validation and you see how they do it.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top