user3037960 February 2016

Knockout.js custom validation rule for logical OR for two input fields

How can I validate two input fields with Knockout.js? The rule is: at least one of the input fields must be filled in.

ko.validation.rules['OR'] = {
    validator: function (val, otherVal) {
        return (val || otherVal);
    },
    message: "you have to fill in at least one of the two input fields!"
};

ko.validation.registerExtenders();


self.description = ko.observable().extend({ OR:  self.title });
self.title = ko.observable().extend({ OR:  self.description });

At the moment: on init only one of the fields are red and one is green - they should both be red on start.

https://github.com/Knockout-Contrib/Knockout-Validation

 self.title = ko.observable().extend({ OR:  self.description });
 self.description = ko.observable().extend({ OR:  self.title });

title is valid but description is not valid on start. when I change the code order to:

self.description = ko.observable().extend({ OR:  self.title });      
self.title = ko.observable().extend({ OR:  self.description });

then its the opposite.

Even the example from the KnockOut contribution doesn't work for me: https://github.com/Knockout-Contrib/Knockout-Validation/wiki/User-Contributed-Rules

ko.validation.rules['requiresOneOf'] = {
  getValue: function (o) {
    return (typeof o === 'function' ? o() : o);
  },
  validator: function (val, fields) {
    var self = this;

    var anyOne = ko.utils.arrayFirst(fields, function (field) {
      var stringTrimRegEx = /^\s+|\s+$/g,
                testVal;

      var val = self.getValue(field);

      if (val === undefined || val === null) 
        return !required;

      testVal = val;
      if (typeof (val) ==         

Answers


user3037960 February 2016

I found the error. Actually it was a chicken-egg-problem.

At the moment when I gave the title or the description to the validation, they were not initialized yet. I changed my code to this and now it works:

//define the validation rule:
ko.validation.rules['Or'] = {
    validator: function (val, params) {
        "use strict";
        return (val !== "" && val !== undefined) || ( params.other() !== "" && params.other() !== undefined);
    },
    message: "you have to fill in at least one of the two input fields!"
};

ko.validation.registerExtenders();


//apply the validation rule:
 self= this;

    self.description = ko.observable();
    self.title = ko.observable();

    self.title.extend({
        or: {
            params: {other: self.description},
            message: "Please fill at least one field!"
        }
    });

    self.description.extend({
        or: {
            params: {other: self.title},
            message: "Please fill at least one field!"
        }});

Post Status

Asked in February 2016
Viewed 2,343 times
Voted 5
Answered 1 times

Search




Leave an answer