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 likeevery(). Older rule versions don't support this functionality.every(item => isString(item)): This built-in method checks every element inmyArrayagainst theisString()validator. It returnstrueonly if all elements are strings.- Handling Optional Arrays: If
myArrayisn'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 returnstruefor empty arrays by default. If you want to block empty arrays, add thesize() > 0check 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
相关产品推荐
相关产品推荐

