本篇体验View Model验证。Knockout的subscribe方法能为View Model成员注册验证规则。

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<style type="text/css">
    .error {
        color: red;
    }
</style>

<input data-bind="value: name, valueUpdate: 'afterkeydown'"/>
<span class="error" data-bind="visible: hasError">最大长度为8!</span>


@section scripts
{
    <script src="~/Scripts/knockout-2.2.0.js"></script>
    <script type="text/javascript">

        //使用构造函数创建一个View Model
        var User = function() {
            this.name = ko.observable("darren");
            this.hasError = ko.observable(false);

            //给name注册一个方法
            this.name.subscribe(function(newValue) {
                this.hasError(newValue && newValue.length > 8);
            }, this);
        };

        ko.applyBindings(new User());
    </script>
}


以上的做法稍显繁琐。其实,使用NuGet上的"Knockout.Validation"是最明智的做法。

通过NuGet安装Knockout.Validation

安装完成后,在Scripts文件夹下多了如下文件。

在Scripts文件夹下创建zh-CN.js,用来汉化。

ko.validation.localize({
    required: '必填字段',
    min: '输入值必须大于等于 {0}',
    max: '输入值必须小于等于 {0}',
    minLength: '至少输入 {0} 个字符',
    maxLength: '输入的字符数不能超过 {0} 个',
    pattern: '请检查此值',
    step: '每次步进值是 {0}',
    email: 'email地址格式不正确',
    date: '日期格式不正确',
    dateISO: '日期格式不正确',
    number: '请输入一个数字',
    digit: '请输入一个数字',
    phoneUS: '请输入一个合法的手机号(US)',
    equal: '输入值不一样',
    notEqual: '请选择另一个值',
    unique: '此值应该是唯一的'
});

Knockout.Validation的基本验证

□ 必填

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<style type="text/css">
    .validationMessage {
        color: red;
    }
</style>

<input data-bind="value: name, valueUpdate: 'afterkeydown'"/>

@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">
        //使用构造函数创建一个View Model
        var User = function() {
            this.name = ko.observable("darren").extend({required:true});
        };

        ko.applyBindings(new User());
    </script>
}


□ 最小值

this.name = ko.observable("darren").extend({ min: 2 });

□ 最大值

this.name = ko.observable("darren").extend({ max: 99 });

□ 最小长度

this.name = ko.observable("darren").extend({ minLength: 3 });

□ 最大长度

this.name = ko.observable("darren").extend({ maxLength: 12 });

□ 邮件

this.name = ko.observable("darren").extend({ email: true });

□ 正则表达式

this.name = ko.observable("darren").extend({ pattern: '^[a-z0-9].$' });

□ 相等

var otherObj = ko.observable();
var myObj = ko.observable().extend({ equal: otherObj });

var myObj = ko.observable().extend({ equal: 2 });

□ 不等

var otherObj = ko.observable();
var myObj = ko.observable().extend({ notEqual: otherObj });

var myObj = ko.observable().extend({ notEqual: 2 });

□ 日期

this.name = ko.observable("").extend({ date: true });

□ 数字,包括小数点

this.name = ko.observable("").extend({ number: true });

□ 整型

this.name = ko.observable("").extend({ digit: true });

□ 同时多个验证规则

this.name = ko.observable().extend({
                required: true,
                maxLength: 3
            });

□ 验证View Model实例

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<style type="text/css">
    .validationMessage {
        color: red;
    }
</style>

<input data-bind="value: name, valueUpdate: 'afterkeydown'"/><br/>
<button id="btn">提交</button>

@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">
        //使用构造函数创建一个View Model
        var User = function() {
            this.name = ko.observable().extend({
                required: true,
                maxLength: 3
            });
        };

        var user = new User();

        ko.applyBindings(user);
        ko.validatedObservable(user);

        $(function() {
            $('#btn').on("click", function() {
                if (user.isValid) {
                    alert('ok');
                }
            });
        });
    </script>
}


以上,必须先使用ko.validatedObservable方法,然后才能使用isValid方法判断是否验证通过。

参考资料:
https://github.com/Knockout-Contrib/Knockout-Validation/wiki

在ASP.NET MVC中使用Knockout实践05,基本验证的更多相关文章

  1. 在ASP.NET MVC中使用Knockout实践01,绑定Json对象

    本篇体验在ASP.NET MVC下使用Knockout,将使用EF Code First创建数据库.最后让Knockout绑定一个Json对象. 创建一个领域模型. namespace MvcAppl ...

  2. 在ASP.NET MVC中使用Knockout实践06,自定义验证、异步验证

    在上一篇中体验了Knockout.Validation的基本验证,本篇体验自定义验证和异步验证. 自定义验证规则 ko.validation有一个rules属性,专门用来存放验证规则,它是一个键值对集 ...

  3. 在ASP.NET MVC中使用Knockout实践09,自定义绑定

    Knockout真正强大之处在于绑定机制,通过data-bind属性值体现绑定,不仅可以绑定值,还可以绑定事件,甚至可以自定义绑定. 从一个例子看Knockou的绑定机制 假设想给一个button元素 ...

  4. 在ASP.NET MVC中使用Knockout实践07,自定义验证信息的位置与内容

    在前两篇中,体验了Knockout的基本验证和自定义验证.本篇自定义验证信息的显示位置与内容. 自定义验证信息的显示位置 通常,Knockout的验证信息紧跟在input后面,通过validation ...

  5. 在ASP.NET MVC中使用Knockout实践08,使用foreach绑定集合

    本篇体验使用 foreach 绑定一个Product集合. 首先使用构造创建一个View Model. var Product = function(data) { this.name = ko.ob ...

  6. 在ASP.NET MVC中使用Knockout实践04,控制View Model的json格式内容

    通常,需要把View Model转换成json格式传给服务端.但在很多情况下,View Model既会包含字段,还会包含方法,我们只希望把字段相关的键值对传给服务端. 先把上一篇的Product转换成 ...

  7. 在ASP.NET MVC中使用Knockout实践03,巧用data参数

    使用Knockout,当通过构造函数创建View Model的时候,构造函数的参数个数很可能是不确定的,于是就有了这样的一个解决方案:向构造函数传递一个object类型的参数data. <inp ...

  8. 在ASP.NET MVC中使用Knockout实践02,组合View Model成员、Select绑定、通过构造器创建View Model,扩展View Model方法

    本篇体验使用ko.computed(fn)计算.组合View Model成员.Select元素的绑定.使用构造器创建View Model.通过View Model的原型(Prototype)为View ...

  9. 在ASP.NET MVC中对手机号码的验证

    在ASP.NET MVC中,可以使用RegularExpression特性来验证手机号码. public class Customer { [Required(ErrorMessage = " ...

随机推荐

  1. Python3安装配置【转】

    不建议卸载python2 可能会导致系统内其他软件无法使用,如果使用最新的Python3那么我们知道编译安装源码包和系统默认包之间是没有任何影响的,所以可以安装python3和python2共存 (前 ...

  2. NEERC Southern Subregional 2011

    NEERC Southern Subregional 2011 A - Bonnie and Clyde solution 双指针搞搞就好. 时间复杂度:\(O(n)\) B - Building F ...

  3. jexus http to https

    一.摘要 1.80端口上只要没有网站使用 hosts=* 这样的配置,jexus会自动将域名跳转到 https 上.也就是说,你把网站默认配置文件default中的hosts=*改成具体的其它的域名, ...

  4. Luogu P1318 积水面积

    题目描述 一组正整数,分别表示由正方体迭起的柱子的高度.若某高度值为x,表示由x个正立方的方块迭起(如下图,0<=x<=5000).找出所有可能积水的地方(图中蓝色部分),统计它们可能积水 ...

  5. php生成随机数

    生成1-10之间的随机数,不重复. 方法一:用shuffle函数. <?php $arr=range(1,10); shuffle($arr); foreach($arr as $values) ...

  6. IntelliJ IDEA快捷键:F12

    The F12 key moves the focus from the editor to the last focused tool window. 将焦点从编辑器移动到最后一个聚焦的工具窗口.

  7. doc文档生成带目录的pdf文件方法

    准备软件: 福昕PDF阅读器 下载地址:http://rj.baidu.com/soft/detail/12882.html?ald 安装福昕PDF阅读器,会自动安装pdf打印机. 准备好设置好各级标 ...

  8. 2017 icpc 沈阳 G - Infinite Fraction Path

    题目大意:有n个点, 每个点有一个数字0 - 9, 第 i 个点只能到 第(i * i + 1)个点,问你在哪个点出发走n次构成的数字串最大. 思路:利用求后缀数组的倍增比较思想, 许多细节需要注意. ...

  9. Garph Coloring

    题意:给了一个有 n 个点 m 条边的无向图,要求用黑.白两种色给图中顶点涂色,相邻的两个顶点不能涂成黑色,求最多能有多少顶点涂成黑色.图中最多有 100 个点 该题是求最大独立集团  最大团点的数量 ...

  10. 035 spark与hive的集成

    一:介绍 1.在spark编译时支持hive 2.默认的db 当Spark在编译的时候给定了hive的支持参数,但是没有配置和hive的集成,此时默认使用hive自带的元数据管理:Derby数据库. ...