1

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?

Moshe Katz
  • 15,992
  • 7
  • 69
  • 116
user2142786
  • 1,484
  • 9
  • 41
  • 74
  • 1
    Your Fiddle features over 400 lines of JavaScript (not exactly a compact reproduction) but there isn't a single line of Knockout Validation in there (at least you don't use any `extend` on your observables to add validation rules). Seems like you're asking us to do your coding for you. – Hans Roerdinkholder Aug 20 '14 at 09:10
  • I tried it but my code stop working that is why i remove validation part from my code – user2142786 Aug 20 '14 at 09:16
  • Right now it's too broad. Don't expect anyone to provide you with a full implementation. Try to implement it yourself, and when you run into an issue, you'll be able to ask a more specific question. And usually those specific questions are already asked (and answered!) by someone before. – Hans Roerdinkholder Aug 20 '14 at 09:18

1 Answers1

2

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

Muhammad Raheel
  • 19,823
  • 7
  • 67
  • 103