之前整理了三篇帖子:
Knockout: 使用CSS绑定和event的blur失去焦点事件, 给未通过校验的输入框添加红色边框突出显示. http://www.cnblogs.com/liuzhendong/p/3596267.html
Knockout: 实践CSS绑定和jQuery的blur失去焦点事件, 给未通过校验的输入框添加红色边框突出显示. http://www.cnblogs.com/liuzhendong/p/3595949.html
Knockout: 实践CSS绑定和afterkeydown事件, 给未通过校验的输入框添加红色边框突出显示; 使用afterkeydown事件自动将输入转大写字母. http://www.cnblogs.com/liuzhendong/p/3595845.html
这三篇讲述的都是同一个主题, 虽然分别用了不同的技术实现, 但大方向都是自己写校验程序的, 今天使用knockout validation插件来做同样的校验工作, 正好可以比较一下可以节省多少代码!
首先要去https://github.com/Knockout-Contrib/Knockout-Validation下载knockout.validation.js, 然后引入自己的代码, 具体如下:
1.htm
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="Lib/require/require.js" data-main="JsDemo5_Main"></script> <style type="text/css"> .error { border: 2px solid red; } input { border: 1px solid #AAA; padding: 4px; } </style> </head> <body> <input id="txtFirstName" type="text" data-bind="value:firstName, validationElement: firstName" /><br /> <input id="txtLastName" type="text" data-bind="value:lastName, validationElement: lastName" /><br /> <input id="txtScore" type="text" data-bind="value:score, validationElement: score" /><br /> <button id="btn" data-bind="click:SubmitClick" >btn</button> <br /><br /> <!--显示错误提示信息 start--> <font color="red"> <b> <span data-bind="validationMessage: firstName"></span> <span data-bind="validationMessage: lastName"></span> <span data-bind="validationMessage: score"></span> </b> </font> <!--显示错误提示信息 end--> </body> </html>
2.JsDemo5_Main.js
require.config({ paths: { "knockout": "Lib/knockout/knockout-2.3.0", "jquery": "Lib/jquery/jquery-1.9.1.min", "knockvalidation": "Lib/knockout/knockout.validation" } }); require(['knockout', 'jquery','knockvalidation'], function ( ko, $, kovalidation) { //数据绑定 ko.validation.configure({ decorateElement: false, registerExtenders: true, messagesOnModified: true, insertMessages: false, parseInputAttributes: true, messageTemplate: null, errorClass : 'error' }); var viewModel = { firstName: ko.observable().extend({ required: { message: '请输入firstName' } }), lastName: ko.observable().extend({ required: { message: '请输入lastName' } }).extend({ minLength: 2, maxLength: 10 }), score: ko.observable().extend({ validation: { validator: function (val, someOtherVal) { if (val != null && val.length >= someOtherVal) { return true; } else { return false; } }, message: '最少要输入6位数字', params: 6 } }), SubmitClick: function () { if (viewModel.errors().length == 0) { //可以提交数据了. alert("ok"); return true; } else { alert("fail"); viewModel.errors.showAllMessages(); return false; } } }; viewModel.errors = ko.validation.group(viewModel); $(document).ready(function () { ko.applyBindings(viewModel); }); });
3.截图
4.总结
使用了knockout.validation插件,确实大大节省了代码量,而且knockout.validation插件也支持写自定义的校验函数,扩展性非常好,因此,值得推荐使用!