在ASP.NET MVC中使用Knockout實踐05,基本驗證

Darren Ji發表於2014-11-02

本篇體驗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>
}

7

 

以上的做法稍顯繁瑣。其實,使用NuGet上的"Knockout.Validation"是最明智的做法。

 

通過NuGet安裝Knockout.Validation

8

 

安裝完成後,在Scripts資料夾下多瞭如下檔案。
9

 

在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

相關文章