Bronzato
Bronzato

Reputation: 9342

How to implement this validation in a Knockout-based form?

I started to work on an ASP.NET MVC4 solution with the SPA template (Single Page Application).

The starting template manage some todo lists with a kind of post-it design.

I slightly modified the template this way:

I have now the ability to edit one element in a form tag like this:

<form data-bind="with: currentTodoList, validate: true">
    <h1>Edition</h1>
    <table>
        <tr>
            <td>ID</td>
            <td><b data-bind="text: todoListId"></b></td>
        </tr>
        <tr>
            <td>User ID:</td>
            <td><input class="required" data-bind="value: userId" /></td>
        </tr>
        <tr>
            <td>Title:</td>
            <td><input class="required" data-bind="value: title" /></td>
        </tr>
        <tr>
            <td>Category:</td>
            <td><input data-bind="value: category" /></td>
        </tr>
    </table>

    <p>
        <button data-bind="click: $parent.saveTodoList">Save</button>
        <button data-bind="visible: todoListId, click: $parent.deleteTodoList">Delete</button>
        <button data-bind="click: $parent.showGrid">Cancel</button>
    </p>
</form>

As you can see above, I set the validate data-binding on the form tag and I have some input element with the class required.

When I test this implementation it doesn't work as expected. Example:

enter image description here

enter image description here

The inverse is also true: userId <--> title. Any idea where is the problem?

Here is a link to download my test VS2012 solution to reproduce the problem.

Upvotes: 1

Views: 431

Answers (1)

Srikanth Venugopalan
Srikanth Venugopalan

Reputation: 9049

Ok, so I played with your markup a little, with slight modification to the view model (not using a list, but editing a single entry).

Take a look at this jsfiddle - http://jsfiddle.net/Zxjrb/1/

I have added a span for validation message for ID and User ID, skipped the span for Title and Category.

<span data-bind='visible: todoListId.hasError, text: todoListId.validationMessage'> </span>

You can see the messages coming up, when Id or UserId field being empty, and that not happening for the title/category fields.

Upvotes: 1

Related Questions