在ASP.NET MVC中使用Knockout實踐07,自訂驗證資訊的位置與內容

來源:互聯網
上載者:User

標籤:style   blog   http   io   color   ar   os   使用   java   

在前兩篇中,體驗了Knockout的基本驗證和自訂驗證。本篇自訂驗證資訊的顯示位置與內容。

 

自訂驗證資訊的顯示位置

 

通常,Knockout的驗證資訊緊跟在input後面,通過validationMessage屬性可以自訂驗證資訊的顯示位置。

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<style type="text/css">
    .error {
        color: red; 
    }
</style>
<div>
    <input type="text" data-bind="value: name"/>
    <p class="error" data-bind="validationMessage: name"></p>
</div>
@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.name = ko.observable().extend({ minLength: 3 });
        };
     
        //建立執行個體
        var product = new Product();
        //驗證設定
        var knockoutValidationSettings = {
            insertMessages: false,
            decorateElement: false,
            errorMessageClass: ‘error‘,
            errorElementClass: ‘error‘,
            errorClass: ‘error‘,
            errorsAsTitle: true,
            parseInputAttributes: false,
            messagesOnModified: true,
            decorateElementOnModified: true,
            decorateInputElement: true
        };
        ko.validation.init(knockoutValidationSettings, true);
       
        //綁定
        ko.applyBindings(product);
       
        $(function () {
            ko.decorateElement = false;
        });
    </script>
}

以上,
● 把驗證資訊顯示在了data-bind屬性值為validationMessage: name的input上
● 由於重新設定了Knockout-Validation,必須使用ko.validation.init()重新初始化
● insertMessages表示是否把驗證資訊顯示在緊跟input的位置
● decorateElement表示是否要為input加上class="error"

 

 

自訂驗證資訊的內容

 

如果想重寫驗證資訊的內容,修改如下:

        var Product = function () {
            this.name = ko.observable().extend({ minLength: { params: 3, message: "要我說最小長度是3" } });
        };

在ASP.NET MVC中使用Knockout實踐07,自訂驗證資訊的位置與內容

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.