You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firestore规则:如何验证数组仅含字符串?禁止循环与递归

Validate Firestore Array Elements Are Strings Without Loops/Recursion

Great question! When you need to ensure every element in myArray is a string without writing manual loops or recursive calls, Firestore's Security Rules 2.0+ have built-in functionality that handles this cleanly.

Core Solution

Use the every() array method (built into Firestore Rules 2.0+) combined with the isString() type-checking function. This method iterates over the array internally (no custom loops/recursion needed) and validates that every element meets your condition.

Complete Rule Example

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /your-target-collection/{document} {
      allow create, update: if
        // Optional: Ensure myArray exists (remove if it's an optional field)
        request.resource.data.keys().has('myArray') &&
        // Validate all elements are strings
        request.resource.data.myArray.every(item => isString(item)) &&
        // Optional: Reject empty arrays (remove if empty arrays are allowed)
        request.resource.data.myArray.size() > 0;
    }
  }
}

Key Details

  • rules_version = '2': Required to access modern array methods like every(). Older rule versions don't support this functionality.
  • every(item => isString(item)): This built-in method checks every element in myArray against the isString() validator. It returns true only if all elements are strings.
  • Handling Optional Arrays: If myArray isn't a required field, adjust the condition to skip validation when the array is missing:
    request.resource.data.keys().has('myArray') 
      ? request.resource.data.myArray.every(item => isString(item)) 
      : true
    
  • Empty Arrays: The every() method returns true for empty arrays by default. If you want to block empty arrays, add the size() > 0 check as shown in the example.

This approach is efficient, adheres to Firestore's best practices, and avoids any custom loops or recursion as requested.

内容的提问来源于stack exchange,提问作者000000000000000000000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:30:08