14

Html form is controlled using Knockout JS and jQuery templates. Basic jQuery validation is in use to validate fields. Form gets serialized to JSON and submitted to MVC controller action using AJAX. MVC controller action performs server-side model validation, adds errors to ModelState.

  1. What's the best practice to return those errors to the client - iterating through errors in ModelState and adding them to key/value collection of errors in the JSON response?

  2. How do you display errors on the client? How do you 'bind' the key/value collection of errors to relevant fields on the model?

Say there is a "name" field on the model, with a corresponding textbox rendered by the jQuery template. How does one take the error for the "name" field in the collection of errors and display the error message beneath the "name" textbox?

    2 Answers 2

    5

    There's two validation plugins for ko.js (found here) that could help you,

    Knock-Knock validation

    Knockout Validation

    You can wire one of those to the mvc unobstrsive validation data injected client side.

    1
    • 10
      After looking at the 2nd option (Knockout Validation) I was wondering how you would be able to map the validation attributes from an MVC view model to the .extend() method in Knockout?
      – Ryan
      CommentedFeb 16, 2012 at 14:28
    4

    If you are using MVC, unobtrusive javascript performs client side validation based on the validation set in your model. You need not perform any additional configuration.

    Having said that, there is no direct way to perform client side validation based on the model using javascript and knockoutjs.

    There are couple of ways of doing it on the client side.

    1. Jquery or any other validation frameworks can perform validation. But you need to have tag. Advantage with this approach is your code will be simple and easy to maintain.
    2. You can perform client side custom validation using javascript and bind the validation messages using knockout. This requires you to create error labels for each of the input variable. Advantage with this approach is you will have complete control over how and what has to be displayed.

    Personally, I had similar requirement in one of the recent projects and I achieved it using custom validation checks and error labels.

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.