在上一篇中体验了Knockout.Validation的基本验证,本篇体验自定义验证和异步验证。
自定义验证规则
ko.validation有一个rules属性,专门用来存放验证规则,它是一个键值对集合类型,key就是自定义验证规则的名称,value是一个json对象。
@{ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}<style type="text/css">
.validationMessage {color: red;}</style><input data-bind="value: name, valueUpdate: 'afterkeydown'"/><br/>
@section scripts{<script src="~/Scripts/knockout-2.2.0.js"></script>
<script src="~/Scripts/knockout.validation.js"></script>
<script src="~/Scripts/zh-CN.js"></script>
<script type="text/javascript">
//自定义验证规则
ko.validation.rules["myCustomValidation"] = {
validator: function(val, otherVal) {return val == otherVal;
},message: '输入值必须和{0}相等'};//注册自定义规则
ko.validation.registerExtenders();//使用构造函数创建一个View Model
var User = function() {this.name = ko.observable().extend({
myCustomValidation: 3});};//创建实例
var user = new User();
//绑定
ko.applyBindings(user);$(function() {});</script>}
还可以把自定义规则以匿名函数的形式放在extend方法之内,还可以同时注册多个自定义验证规则。
@{ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}<style type="text/css">
.validationMessage {color: red;}</style><input data-bind="value: name, valueUpdate: 'afterkeydown'"/><br/>
@section scripts{<script src="~/Scripts/knockout-3.2.0.js"></script>
<script src="~/Scripts/knockout.validation.js"></script>
<script src="~/Scripts/zh-CN.js"></script>
<script type="text/javascript">
//使用构造函数创建一个View Model
var User = function () {this.name = ko.observable().extend({
validation: [{validator: function (val, someOtherVal) {return val == someOtherVal;
},message: '必须是 5',params: 5
}]});};//创建实例
var user = new User();
//绑定
ko.applyBindings(user);$(function () {});</script>}
自定义异步验证规则
假设,现在需要根据前台输入的Product的Id来判断是否存在。
在HomeController中提供一个根据id判断是否存在的Action方法,返回json格式。
static readonly IProductRepository repository = new ProductRepository();......[HttpPost]public JsonResult JudgeProduct(int id){//获取所有记录
var allProducts = repository.GetAll();//获取所有的ids
IEnumerable<int> ids = from p in allProductsselect p.Id;if (ids.Contains(id))
{return Json(new {msg = true});}else
{return Json(new { msg = false });}}
前台需要给View Model实例注册异步验证规则。
@{ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}<style type="text/css">
.validationMessage {color: red;}</style><input data-bind="value: id, valueUpdate: 'afterkeydown'"/><br/>
@section scripts{<script src="~/Scripts/knockout-3.2.0.js"></script>
<script src="~/Scripts/knockout.validation.js"></script>
<script src="~/Scripts/zh-CN.js"></script>
<script type="text/javascript">
//使用构造函数创建一个View Model
var Product = function () {this.id = ko.observable();
this.isExist = ko.validatedObservable(true);};//创建实例
var product = new Product();
//给实例成员注册自定义验证逻辑
product.id.subscribe(function () {$.post('@Url.Action("JudgeProduct","Home")', { id: product.id() }, function (data) {product.isExist(data.msg);});});//给实例成员实施验证
product.id.extend({validation: {validator: function (val, param) {return product.isExist();
},message: "数据库中没有此款产品"
}});//绑定
ko.applyBindings(product);$(function () {});</script>}
以上,通过subscribe方法,给Product的实例字段id注册了一个自定义验证规则,向服务端发送POST请求,把返回的结果赋值给Prouct的实例字段isExist。再给Product的实例字段id扩展自定义验证规则,返回Product实例字段isExist的值,如果为true,表示验证通过,反之,验证不通过。