JSFiddle - React, Tailwind, and code Playground
by gurkavcu
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.2.1/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.4/knockout.validation.min.js"></script>
<p data-bind="with: itemToAdd">
<label>Id <input data-bind="value: Id" /></label>
<label>Account name <input data-bind="value: Name, valueUpdate: 'afterkeydown'" /></label>
<button type="button" data-bind="click: $root.createItem">Add</button>
</p>
<hr/>
<div data-bind="with: itemToAdd">
<b>Item To Add:</b> <br>
<p>Id: <span data-bind="text: Id"></span></p>
<p>Name: <span data-bind="text: Name"></span></p>
<p>UserId: <span data-bind="text: UserId"></span></p>
</div>
<hr/>
<ul data-bind="foreach: items">
<li>
Id: <span data-bind="text: Id"></span><br>
Name: <span data-bind="text: Name"></span>
</li>
</ul>
CSS
label { width: 50px; }
button { display: block; }
.validationMessage { color: Red; }
.customMessage { color: Orange; }
li:nth-child(2n+1) { background-color: #f9f9f9; }
JavaScript
/*ko.validation.configure({
registerExtenders: true,
messagesOnModified: true,
insertMessages: true,
parseInputAttributes: true,
messageTemplate: null
});*/
var activeAccount = function(data) {
this.Id = ko.observable(data.id);
this.Name = ko.observable(data.name).extend({ required: { message: 'Enter account name.'} });
this.UserId = ko.observable(1);
this.errors = ko.validation.group(this);
};
var viewModel = {
items: ko.observableArray([]),
itemToAdd: ko.observable(new activeAccount({})),
createItem: function (item) {
if (item.errors().length == 0) {
viewModel.items.push(item);
viewModel.itemToAdd(new activeAccount({}));
} else {
item.errors.showAllMessages();
}
}
};
ko.applyBindings(viewModel);