2

I am new to knockout, and trying to workout how to use validations. We have the following piece of code -

 var MyObjectModel = function(myObject){
 var self = this;
 self.myNumber = ko.observable(myObject.number).trimmed();
 self.myNumber.extend({
 minLength: {
 params: 7,
 message: "My Number is too short."
 },
 maxLength: {
 params: 7,
 message: "My Number is too long."
 }
 });
 self.errors = ko.validation.group(self);
}

Now I would like to change the code so that either the length of myObject.number should be either exactly 7, or the field should be empty. How do I go about making this change ?

Any help would be appreciated. In case you think something is not clear, please let me know so I can elaborate more.

asked Jan 14, 2013 at 9:39
2
  • 1
    What is your problem with your current approach with minLength and minLength? What is not working exactly? Because it seems it is working fine: jsfiddle.net/X9mDy/1 it is only valid is you enter 7 digits long. Commented Jan 14, 2013 at 9:43
  • minLength and maxLength work fine for me. What I also want is to make the field optional. So if the user has put in any value, it should be exactly 7 characters long, else it should be empty. I tried required:false, but it does not help. Any idea where I could be going wrong ? Commented Jan 14, 2013 at 9:50

1 Answer 1

3

You can use a custom pattern to it:

var MyObjectModel = function(myObject){
 var self = this;
 self.myNumber = ko.observable(myObject.number).trimmed();
 self.myNumber.extend({
 pattern: {
 params: '^[0-9]{7}$|^$',
 message: "My Number must have 7 chars or stay empty."
 }
 });
 self.errors = ko.validation.group(self);
}
answered Jan 14, 2013 at 10:11
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.