Reputation: 1482
I created some input fields using KnockoutJS, and now I want to validate them.
http://jsfiddle.net/sohimohit/43zkoszu/12/
I tried it using validation plugin but it doesn't work.
I added that plugin and used it as mentioned but didn't get the solution. When you click on "add field" a form appears; I want to make the name
field required and branch id
as numeric. However, when I click on "add fields" it doesn't get added until the form is validated.
How can I achieve this?
Upvotes: 1
Views: 10264
Reputation: 19882
You are not doing validation properly. I recommend this method
Set some settings
ko.validation.configure({
insertMessages: false,
decorateElement: true,
errorElementClass: 'error-element',
errorClass: 'error-element',
errorsAsTitle: true,
parseInputAttributes: false,
messagesOnModified: true,
decorateElementOnModified: true,
decorateInputElement: true
});
Make inputs bind with validationElement
<input type="text" placeholder="Name" data-bind="value:name,validationElement:name">
<input type="text" placeholder="Branch" data-bind="value:branch,validationElement:branch">
Extend observables
self.name = ko.observable().extend({required:true})
self.branch = ko.observable().extend({required:true,digit: true})
Now apply the rule. I prefer group
var data = [
self.name,
self.branch
]
self.Errors = ko.validation.group(data);
Now on add button wrap your code
self.Add = function(){
if(self.Errors.length == 0){
.
.
.
//Your code here
}else{
self.Errors.showAllMessages()
}
}
Hope it helps
Upvotes: 2