Knockout-Contrib / Knockout-Contrib/Knockout-Validation

Nested "required" fields pass validation when they are undefined and/or empty

Open
#637 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
1k
Forks
366
PR merge metrics
No merged PRs in 30d

Description

Observables within observable arrays which are "required" are passing validation even if they are undefined or empty.

To reproduce the issue, please see this JSFiddle. I have a form which collects information about dogs' names and breeds. The "Dog Breed" field is required. Also note that I have followed the examples here on how to validate nested values.

  function KnockoutViewModel() {
    var self = this;
    self.dogs = ko.observableArray([new Dog()]);
    self.submitForm = function() {
      console.log(self.dogs()[0].Breed());
    };
    
    self.validationObject = ko.validatedObservable({
        dogs: self.dogs
    });
  }

  function Dog() {
    var self = this;
    self.Name = ko.observable();
    self.Breed = ko.observable().extend({
      required: {
        params: true,
        message: "The dog's breed field is required."
      }
    });
    
    self.validationObject = ko.validatedObservable({
        Breed: self.Breed.extend({
            required: true
        })
    });
  }

To reproduce the issue:

  1. Submit the form without a value in the "Dog Breed" field. validation successful
  2. Enter a value into the "Dog Breed" field, delete it, and re-submit the form. validation successful
  3. Enter a value into the "Dog Breed" field, submit the form, delete the value again, and resubmit the form. validation failed

I would expect (3) but not (1) and (2). Is this the intended behavior?

Note: I originally encountered this issue and described it in #636, but I'd initially missed the part of the documentation that states that special configuration is required to validate observables within observable arrays.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked JSFiddle reproduction and the repository's documentation on validating nested values. Trace how required validation is collected for observables inside observable arrays, then reproduce the three submission cases and add coverage for the expected failures in cases (1) and (2).

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
frontend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.