转自:https://blog.csdn.net/afandaafandaafanda/article/details/48245611
Knockout 将View与Data进行双向绑定,在View上的数据改变能够自动反映到View所绑定的数据源上,同理,数据源的改变也能够立即反映到相关的View上。我们在使用Knockout的时候,还需要做的一个事情就是数据校验,在这方面,Knockout提供了很好的校验机制。
1.下载安装
下载之后我们的工程的javascript目录下面就有了knockout.js及knockout.validation.js文件了!
2.示例
引入相关文件:
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/knockout-2.3.0.js"></script>
<script src="~/Scripts/knockout.validation.js"></script>
页面代码:
@{
ViewBag.Title = "Home Page";
}
<style type="text/css">
.validationMessage {
color: red;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
var Person = function() {
var self = this;
self.name = ko.observable().extend({
required:{ params: true, message: "please input name."} ,
maxLength: 6
});
self.age = ko.observable().extend({
required: true,
number: {
params: true,
message: "必须是数字",
},
max:100
});
self.email = ko.observable().extend({
required: {
params: true,
message: "请填写Email"
},
email: {
params: true,
message: "Email格式不正确"
}
});
self.birthday = ko.observable().extend({
required: true,
date: {
params: true,
message: "日期格式不正确"
}
});
self.score = ko.observable().extend({
required: true,
pattern: {
params: /^\d+[\.]?\d{0,2}$/g,
message: "必须是数字,并且最多两位小数!"
}
});
self.submit = function() {
if (person.isValid().length == 0) {
alert('ok');
} else {
alert("error");
}
};
};
var person = new Person();
ko.applyBindings(person);
person.isValid = ko.validation.group(person);
});
</script>
<br />
<fieldset>
<legend>Add Person</legend>
<div>Name:</div>
<div>
<input data-bind="value: name" />
</div>
<div>
Age:
</div>
<div>
<input data-bind="value: age" />
</div>
<div>
Email:
</div>
<div>
<input data-bind="value: email" />
</div>
<div>
Score:
</div>
<div>
<input data-bind="value: score" /><br /><br />
</div>
<div>
<button id="btn" data-bind="click:submit">submit</button>
</div>
</fieldset>
效果如下:
3.总结
knockout自动捕获了控件的鼠标移开事件,自动进行校验。在提交的时候,通过isValidate来决定是否提交表单.
---------------------
作者:feng1456
来源:CSDN
原文:https://blog.csdn.net/afandaafandaafanda/article/details/48245611
版权声明:本文为博主原创文章,转载请附上博文链接!