Validation in knockout js input fields

[亡魂溺海] 提交于 2019-12-11 07:57:19

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/25400794/validation-in-knockout-js-input-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!