2015-10-06 35 views
3

下面是數據庫模式:驗證一個火力地堡鍵是整數

enter image description here

下面是規則:

"notifications": { 
    "$year": { 
     ".read": "false", 
     ".write": "!data.exists()", 
     "$month": { 
      ".read": "false", 
      ".write": "!data.exists()", 

      "$day": { 
       ".read": "false", 
       ".write": "!data.exists()", 

       "$hour": { 
        ".read": "false", 
        ".write": "!data.exists()", 

        "$minute": { 
         ".read": "false", 
         ".write": "!data.exists()", 
         "$data": { 
          ".read": "false", 
          ".write": "!data.exists()" 
         } 
        } 
       } 
      } 
     } 
    } 

我如何可以驗證(使用 「.validate」 或」。寫「規則),用戶可以只輸入整數到樹中?或者有一些解決方法?

我想要實現的是創建只寫(沒有刪除或更新)日誌,它具有一些結構並將在稍後處理。我可以改變結構,例如像2015-10-6-17-30這樣的關鍵或其他東西。我無法相信Firebase沒有這種情況。

更新: 這不是重複的,我正在尋找一個解決方法,或其他能夠幫助我實現我所追求的目標的東西。

+0

[驗證Firebase密鑰]的可能重複(http://stackoverflow.com/questions/32933181/validating-a-firebase-key) –

+0

更新:這不是重複的,我正在尋找解決方法或其他否則這將幫助我實現我所追求的目標。 – SM79

回答

12

要驗證的關鍵是一個數字:

{ 
    "$key": { 
    ".validate": "$key.matches(/^[0-9]+$/)" 
    } 
} 

但請閱讀array-like behaviors in Firebase。提示:可能使用「y2015」,「m12」等前綴來避免使用數字時出現的意外結果。

+0

非常感謝答案和前綴提示! – SM79

2

如果使用推送ID適用於您,以下是您可以使用的安全規則結構。

{ 
    "notifications": { 
     "$notification_id": { 
      ".write": "!data.exists()", 
      ".read": "false", 
      ".validate": "newData.hasChildren(['time', 'state', 'message'])", 
      "time": { 
       ".validate": "newData.val().matches(/YOUR REGEX/)" 
      }, 
      "state": { 
       ".validate": "" 
      }, 
      "message": { 
       ".validate": "" 
      } 
     } 
    } 
} 

顯然你需要填空。這裏主要的是你可以使用正則表達式來匹配時間字段。

的實際數據會看起來像:

{ 
    "notifications": { 
     "-K-z5koYf8mYZu5OfSGR": { 
      "time": "2015-10-06-17-30", 
      "state": 1, 
      "message": "foo" 
     }, 
     "-K-z5koYf8mYZwgwsfGx": { 
      "time": "2015-10-06-17-30", 
      "state": 1, 
      "message": "bar" 
     } 
    } 
} 
+0

可以驗證密鑰。 – Kato

+0

不知道。答案已更新。 –