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
Abhinav Manchanda
6,6603 gold badges42 silver badges49 bronze badges
-
1What 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.nemesv– nemesv2013年01月14日 09:43:58 +00:00Commented 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 ?Abhinav Manchanda– Abhinav Manchanda2013年01月14日 09:50:37 +00:00Commented Jan 14, 2013 at 9:50
1 Answer 1
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
Gabriel Gartz
2,87024 silver badges24 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Explore related questions
See similar questions with these tags.
lang-js