Knockout.js validation on observableArray requires all items (no null fields)


Maceika

I wrote the following example using knockout.

HTML

<script id="customMessageTemplate" type="text/html">
    <em class="customMessage" data-bind='validationMessage: field'></em>
</script>
<fieldset>
    <legend>User: <span data-bind='text: errors().length'></span> errors</legend>
    <label>First name: <input data-bind='value: firstName'/></label>
    <label>Last name: <input data-bind='value: lastName'/></label>    

    <table>
    <thead>
        <tr><th>Value</th></tr>
    </thead>
    <tbody data-bind="foreach: captcha">
        <tr>
            <td><input data-bind="value: value" type="test" /></td>
        </tr>
    </tbody>
</table>

<button type="button" data-bind='click: submit'>Submit</button>

knock out

ko.validation.rules.pattern.message = 'Invalid.';


ko.validation.configure({
    registerExtenders: true,
    messagesOnModified: true,
    insertMessages: true,
    parseInputAttributes: true,
    messageTemplate: null
});


var captcha = function (val) {
    return val == 11;
};

var mustEqual = function (val, other) {
    return val == other();
};

var viewModel = {
    firstName: ko.observable().extend({ required: true }),
    lastName: ko.observable().extend({ required: true }),
    captcha: ko.observableArray([{value: "test"}]),


    submit: function () {
        if (viewModel.errors().length == 0) {
            alert('Thank you.');
        } else {
            alert('Please check your submission.');
            viewModel.errors.showAllMessages();
        }
    }
};


viewModel.errors = ko.validation.group(viewModel);

ko.applyBindings(viewModel);

What should I add to the observableArray to require all items in this array, like the usual observable objects refer to the input fields FirstName and LastName in the presented example?

you

I'm not sure if this is what you expect. If you want to add validation for each object of an observableArrayyou can do the following:

Create a captchaViewModelfunction and add validation requiredto the valueproperty

var captchaViewModel = function(val) {
  this.value = ko.observable(val).extend({
    required: true
  });
 // other properties if any
}

Then change yours viewModelto:

var viewModel = {
  firstName: ko.observable().extend({ required: true }),
  lastName: ko.observable().extend({ required: true }),
  captcha: ko.observableArray([new captchaViewModel("test")]),

  submit: function() {
    if (viewModel.errors().length == 0) {
      alert('Thank you.');
    } else {
      alert('Please check your submission.');
      viewModel.errors.showAllMessages();
    }
  }
};

You also need to add properties and set them groupingin the configuration .deep: true

ko.validation.configure({
   .......
   .......
  // "deep" indicates whether to walk the ViewModel (or object) recursively, 
  // or only walk first-level properties
  grouping: { deep: true }
});

Here is a fiddle for testing

Related


Knockout JS - Modify properties of items in observableArray

PercivalMcGullicuddy I'm trying to update the numbers shown in red to reflect the position of each item in the observableArray after repositioning an item. You can see my current code here : http://jsfiddle.net/BV87N/ It didn't behave as I expected. I have a f

Knockout validation requires unknown knockout js file

Durr code I'm developing a coredova app using require js and culling js, when I use culling validation, it doesn't work, it shows " Script error for: culling ". It shows the following in the inspect element under the network, www/js/knockout.js 404 not found,

Knockout validation requires unknown knockout js file

Durr code I'm developing a coredova app using require js and culling js, when I use culling validation, it doesn't work, it shows " Script error for: culling ". It shows the following in the inspect element under the network, www/js/knockout.js 404 not found,

Knockout: Update items in observableArray

Jenluca Scarsley I am trying to update an object in an observableArray like this: var vm = { tests: ko.observableArray([{input: 'bar'}]) }; vm.tests.push(ko.observable({input: 'foo'})); ko.applyBindings(vm); setTimeout(function () { vm.tests()[1]()

Knockout: Update items in observableArray

Jeanluca Scaleri I am trying to update an object in an observableArray like this: var vm = { tests: ko.observableArray([{input: 'bar'}]) }; vm.tests.push(ko.observable({input: 'foo'})); ko.applyBindings(vm); setTimeout(function () { vm.tests()[1]()

Knockout: Update items in observableArray

Jenluca Scarsley I am trying to update an object in an observableArray like this: var vm = { tests: ko.observableArray([{input: 'bar'}]) }; vm.tests.push(ko.observable({input: 'foo'})); ko.applyBindings(vm); setTimeout(function () { vm.tests()[1]()

Knockout: Update items in observableArray

Jeanluca Scaleri I am trying to update an object in an observableArray like this: var vm = { tests: ko.observableArray([{input: 'bar'}]) }; vm.tests.push(ko.observable({input: 'foo'})); ko.applyBindings(vm); setTimeout(function () { vm.tests()[1]()

Knockout: Update items in observableArray

Jenluca Scarsley I am trying to update an object in an observableArray like this: var vm = { tests: ko.observableArray([{input: 'bar'}]) }; vm.tests.push(ko.observable({input: 'foo'})); ko.applyBindings(vm); setTimeout(function () { vm.tests()[1]()

Knockout.js validation on hidden fields

Wizlock I'm implementing knockout validation for my form and I only need to fill in the field when it is displayed. Depending on the selection of other fields in the form, some controls may be hidden by visible:hidden or display:none. How can I make these fiel

Knockout.js validation on hidden fields

Wizlock I'm implementing knockout validation for my form and I only need to fill in the field when it is displayed. Depending on the selection of other fields in the form, some controls may be hidden by visible:hidden or display:none. How can I make these fiel

Sort observableArray with Additions Knockout JS

User 1535191 I'm trying to get my observableArray sorted alphabetically and add a new item to the list when "sort" is clicked. Can anyone shed some light on what I'm doing wrong here? thanks, Jason …………………… https://jsfiddle.net/jaloomis111/tssLxbo0/ <input dat

Custom filter knockout js observableArray

Jonah Juss I have an observableArray with a test package and I want to filter based on the text in the search field. The filter is updated after each keystroke, so I'm looking for the most efficient way to do it. Check out this JS fiddle for a simplified versi

knockout.js: No concat on observableArray

Kippie Only starting with knockout.js, but already running into some trouble when trying to make a computed method based on 2 different observableArrays Using the documentation on knockout.js' website, I've created the following viewmodel: var Cart = function(

Updating observables in ObservableArray knockout js

Mahari I have an observableArray and an observable as below. self.unreadcount = ko.observable(); self.searchFilters = ko.observableArray([ {label: "A", active: ko.observable(false), count1: self.unreadcount()}, {label: "B", active: ko.observable(false

Knockout.js ContentEditable ObservableArray

Adam Fraser I'm trying to allow editing items in a string array like this: http://jsfiddle.net/adamfraser/sr4Fg/44/ html <h4> edit </h4> <ul class="list" data-bind="foreach:titles"> <li class="title" data-bind="editableHTML:$data" contenteditable="true"></li

Custom filter knockout js observableArray

Jonah Juss I have an observableArray with a test package and I want to filter based on the text in the search field. The filter is updated after each keystroke, so I'm looking for the most efficient way to do it. Check out this JS fiddle for a simplified versi

Knockout js observableArray not getting updated

Nikita Fedorov I am trying to update an observable array from response data. I'm sure I'm missing something simple, but I don't know why it doesn't work? function addWitness() { $.post("AddWintess", { Witnesses: [{ LastName: "test1", FirstNa

Knockout update observableArray items not reflected in UI?

bridge Problem when my viewModel has observableArray(self.images) and I want to change one property(mm) to reflect on UI In the real code, the image is loaded from the server and mapped to the object DOcImage Here's the code instructions, based on other questi

Knockout observableArray - added items not showing in view

Garip Trying to add an item to observableArray in culling. While the item is indeed added to the view model, it is not added to the view. Seems to be related to using ko.mapping.fromJS. Reproduces the problem I'm facing here: function ViewModel() { var vm

Knockout update observableArray items not reflected in UI?

bridge Problem when my viewModel has observableArray(self.images) and I want to change one property(mm) to reflect on UI In the real code, the image is loaded from the server and mapped to the object DOcImage Here's the code instructions, based on other questi

Knockout JS cannot access elements of observableArray

Karthi1234 I created culled observable array and added elements like below, define(['ojs/ojcore', 'knockout', 'jquery', 'ojs/ojtable', 'ojs/ojarraytabledatasource', 'ojs/ojrouter'], function(oj, ko, $) { function CustomerViewModel() { var self = th

Knockout JS can't update observableArray

Lex So I'm trying to add something to the observable array, but it won't update. The problem is not the first level content, but the subarrays. This is a short comment. Basically I have this function to declare comments function comment(id, name, date, comment

Knockout JS can't update observableArray

Lex So I'm trying to add something to the observable array, but it won't update. The problem is not the first level content, but the subarrays. This is a short comment. Basically I have this function to declare comments function comment(id, name, date, comment

Knockout.js bind observableArray to bytes

Drisan James I'm trying to bind an array of values from a checkbox list to a model with a bytes property type. So I have {"1","2","3"} returned from the checkbox selection, before reaching the model, I need the file in bytes so I can pass it to the model corre