敲除js输入字段中的验证 [英] Validation in knockout js input fields
问题描述
我使用KnockoutJS创建了一些输入字段,现在我想对其进行验证.
I created some input fields using KnockoutJS, and now I want to validate them.
http://jsfiddle.net/sohimohit/43zkoszu/12/
我使用验证插件尝试了此操作,但是它不起作用.
我添加了该插件并如前所述使用了它,但没有得到解决方案.当您单击添加字段"时,将出现一个表格;我想将name
字段设为必需,将branch id
设为数字.但是,当我单击添加字段"时,只有在验证表单之后,它才会被添加.
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.
我该如何实现?
推荐答案
您没有正确进行验证.我推荐这种方法
You are not doing validation properly. I recommend this method
设置一些设置
ko.validation.configure({
insertMessages: false,
decorateElement: true,
errorElementClass: 'error-element',
errorClass: 'error-element',
errorsAsTitle: true,
parseInputAttributes: false,
messagesOnModified: true,
decorateElementOnModified: true,
decorateInputElement: true
});
使输入与validationElement绑定
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">
扩展可观察范围
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()
}
}
希望有帮助
这篇关于敲除js输入字段中的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!