BackboneJS - 模型驗證



說明

驗證使用者提供的模型和輸入。如果輸入無效,則返回指定錯誤訊息;如果輸入有效,則不指定任何內容,只顯示結果。

語法

model.validate(attributes,options)

引數

  • 屬性 − 這些屬性定義模型的屬性。

  • 選項 − 包括 true 作為驗證屬性的選項。

示例

<!DOCTYPE html>
<html>
   <head>
      <title>Model Example</title>
      <script src = "https://code.jquery.com/jquery-2.1.3.min.js"
         type = "text/javascript"></script>
      
      <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"
         type = "text/javascript"></script>
      
      <script src = "https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"
         type = "text/javascript"></script>
   </head>
   
   <body>
      <script type = "text/javascript">
         var Person = Backbone.Model.extend ({
            defaults: {
               name: 'john',
               age: 25,
               occupation: 'working'
            },
            initialize : function() {
               this.on("invalid",function(model,error) {
                  document.write(error);
               });
            },
            validate: function(attributes) {
               if ( attributes.age < 25 ) {
                  return 'Person age is less than 25, please enter the correct age!!! ';
               }
               if ( ! attributes.name ) {
                  return 'please enter the name!!!';
               }
            },
         });
         var person = new Person();
         person.on('invalid', function() {
            this.arguments;
         });
         person.set({ age : '20' }, { validate : true });
      </script>
      
   </body>
</html>

輸出

執行以下步驟,瞭解以上程式碼的工作原理 −

  • 將以上程式碼另存為 validate.htm 檔案。

  • 在瀏覽器中開啟此 HTML 檔案。

backbonejs_model.htm
廣告
© . All rights reserved.