Max value and numerical validation in KnockoutJS
Asked Answered
M

2

0

How do I implement a max value validation and check if the observable's value is numerical, something like:

self.MyInteger = ko.observable().extend({ numeric: 2 })
                               .extend({ maxValue: { params: 255, message: "MyInteger cannot be greater than 255" } });
Merilyn answered 21/3, 2017 at 8:41 Comment(1)
could you show extender numeric and maxValue ???Cuspidor
D
2

sounds like you might be after the knockout validation plugin. https://github.com/Knockout-Contrib/Knockout-Validation

run the snippet below. entering a non digit or something more than 255 will cause the message to display.

function model() {
  var self = this;
  this.myObj = ko.observable().extend({ digit: true }).extend({ max: 255});
  }
  
  var mymodel = new model();

$(document).ready(function() {
  ko.validation.init();
  ko.applyBindings(mymodel);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.min.js"></script>

enter a digit less than or equal to  255 <input type="text" data-bind="textInput: myObj">

<p>
  Enter something other than a digit or over 255 will cause an error.
</p>
Declinature answered 21/3, 2017 at 23:29 Comment(0)
Z
0

To show error message after validating the observable object, you can do the following:

var ViewModel = function() {
  var self = this;
  self.myInteger = ko.observable().extend({ validation: "Please pass numerical value that is less than 255" });
}

ko.extenders.validation = function (target, overrideMessage) {

  target.hasError = ko.observable();
  target.validationMessage = ko.observable();

  function validate(newValue) {
    // write your validation here
    // check if it is numerical
    // check if it is less than the max value
    var passTheValidation = true;
    target.hasError(!passTheValidation);
    target.validationMessage(passTheValidation ? "" : overrideMessage || "This failed the validation");
  }

  //initial validation
  validate(target());

  //validate whenever the value changes
  target.subscribe(validate);

  //return the original observable
  return target;
}

Then show the error message like this

<div>
  <input data-bind='value: myInteger, valueUpdate: "afterkeydown"' />
  <span data-bind='visible: myInteger.hasError, text: myInteger.validationMessage'> </span>
</div>

There is a good reference in the website regarding this extenders http://knockoutjs.com/documentation/extenders.html

Zinfandel answered 21/3, 2017 at 9:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.