17

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 });
}
Simon
  • 33,714
  • 21
  • 133
  • 202
Ryan
  • 4,354
  • 2
  • 42
  • 78
  • Are you using Data Annotations on your C# models and using EditorFor to populate clientside validation rules, or would you like to? You can use the same unobtrusive clientside validation that MVC has built in that you might use for standard MVC style forms with not too much work (at least in MVC3 with the Internet Application template). – kendaleiv Feb 17 '12 at 22:27
  • Please see my edits in the original – Ryan Feb 18 '12 at 03:27
  • This is a very intriguing approach and I have given it a lot of thought. I've been thinking about generating behaviour code from C# to Javascript. That said, I think you'll have to create something that reflects the model and generates javascript. Maybe just the validation part and let the mapping plugin do what it does. The combination of the mapping and the generated validation code could give you what you need. The reason why I think you need to generate the validation code is because I think you'll have a hard time generating the validation code using only Javascript, but I may be wrong. – Mikael Östberg Feb 20 '12 at 10:22
  • How are you currently generating the markup in your view? Do you manually add the data-bind="value: someProp"? – madcapnmckay Feb 29 '12 at 17:34

4 Answers4

7

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.

Kev
  • 118,037
  • 53
  • 300
  • 385
Francesco Abbruzzese
  • 4,139
  • 1
  • 17
  • 18
  • It would be great if you could start us off in how you implemented it using MVC Controls Toolkit. Many thanks – Ian Feb 02 '16 at 10:51
5

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.

pilavdzice
  • 958
  • 8
  • 27
  • +1 I like the simplicity of your solution. I'm currently struggling with jQuery valdiate for non-required fields and Knockout and your answer pointed me in a new direction. – David Robbins Feb 08 '13 at 16:17
1

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.

Community
  • 1
  • 1
kendaleiv
  • 5,793
  • 3
  • 28
  • 38
  • 4
    This is not the preferred way to validate KnockoutJs. You don't want to validate the form elements. You want to validate the view model. – Mikael Östberg Feb 20 '12 at 10:14
  • 2
    Is there an easy way to reuse DataAnnotations or FluentValidator .Net code with Knockout validation and have it validate the Knockout viewmodel? I'd rather avoid creating and maintaining two sets of validation rules, but this may be even more difficult if the Knockout viewmodel and the .Net model do not match or are too dissimilar. – kendaleiv Feb 25 '12 at 06:32
  • "This is not the preferred way to validate KnockoutJs". Why? Validation is connected to user inputs and input elements are usually mapped to model properties. Displaying error messages that are not connected to an input field but to some model property that is not visible to the user might confuse the user a lot. – Francesco Abbruzzese Feb 29 '12 at 21:43
0

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.

Mikael Östberg
  • 16,982
  • 6
  • 61
  • 79