Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout validation: Dynamic constraints

I'm using Durandal, which in turn leverages off of Knockout.

I want to be able to Change validation lengths dynamically

enter image description here

Fiddle

The fiddle seems to be behaving slightly different than my "working" solution, but its still not doing what I'm wanting/expecting it to.

Viewmodel JS:

[Attempt 1]

define(function () {

   var self = this;

   self.userInfo = {       
        IdOrPassportNumber: ko.observable().extend({
            required: true,
            pattern: {
                message: 'A message',
                params: /some regex/
            }
        }),
        IdType: ko.observable()
    },

    self.isIdValid = ko.validatedObservable({ 
         IdOrPassportNumber: self.userInfo.IdOrPassportNumber 
    });

    self.userInfo.IdOrPassportNumber.subscribe(function (value) {
          if (isIdValid.isValid()) {
               console.log('YOLO!');
          }
    });

    self.userInfo.IdType.subscribe(function (value) {
        console.log(value);
        if (value === 'Passport') {
            self.userInfo.IdOrPassportNumber.extend({ maxLength: 15 });
        } else {
            self.userInfo.IdOrPassportNumber.extend({ maxLength: 13 });
        }
    });    

    var viewModel = {
        userInfo: self.userInfo
    };

    viewModel["errors"] = ko.validation.group(viewModel.userInfo);
    viewModel["errors"].showAllMessages();

    return viewModel;
});

What seems to be happening is that when i start typing i get the max & min validation of 13, but if i continue typing the validation changes to 15. I have tried another route of, setting the min & max length in the initial observable extend EG, just after the regex, and then setting the min and max length to use an observable, to no success.

[Attempt 2]

   self.userInfo = {       
       IdOrPassportNumber: ko.observable().extend({               
            maxLength: self.maxLength(), 
            minlength: self.maxLength()
       }),
       IdType: ko.observable()
   },

   self.maxLength = ko.observable();

   self.userInfo.IdType.subscribe(function (value) {

          if (value === 'Passport') {
             self.maxLength(15)
          } else {
              self.maxLength(3)
          }
    });
like image 824
Rohan Büchner Avatar asked Jun 26 '13 07:06

Rohan Büchner


1 Answers

Here is the solution that worked for me:

I made use of the custom validation feature, more specifically the single use custom validation as this wont be re-used elsewhere.

[Attempt 3]

    self.userInfo = {    
        IdOrPassportNumber: ko.observable().extend({
            required: true,
            pattern: {
                message: 'A message',
                params: /some regex/
            },
            validation: {
               validator: function (val) {
                   if (self.userInfo.IdType() === 'Id') { 
                      return val.length === 13; 
                   } else { 
                      return val.length === 15; 
                   }
                },
               message: function () {
                  if (self.userInfo.IdType() === 'Id') {
                    return 'Required: 13 characters';
                  } else {
                    return 'Required: 15 characters';
                  }
               }
            }
        })
     }
like image 81
Rohan Büchner Avatar answered Sep 19 '22 15:09

Rohan Büchner