Data validation rules in Firebase - Commands & Configuration
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { // Match all documents in the 'users' collection match /users/{userId} { allow read, write: if request.auth != null && request.auth.uid == userId; allow create: if request.resource.data.keys().hasAll(['name', 'age']) && request.resource.data.name is string && request.resource.data.name.size() > 0 && request.resource.data.age is int && request.resource.data.age >= 13 && request.resource.data.age <= 120; allow update: if request.resource.data.keys().hasOnly(['name', 'age']) && request.resource.data.name is string && request.resource.data.name.size() > 0 && request.resource.data.age is int && request.resource.data.age >= 13 && request.resource.data.age <= 120; allow delete: if false; // prevent deleting user documents } } }
This file sets rules for the Firestore database.
rules_version: Specifies the version of rules syntax.
service cloud.firestore: Applies rules to Firestore.
match /databases/{database}/documents: Applies rules to all documents.
match /users/{userId}: Targets documents in the 'users' collection.
allow read, write: Allows only authenticated users to read/write their own data.
allow create: Checks that new data has 'name' and 'age' fields, with 'name' as a non-empty string and 'age' as an integer between 13 and 120.
allow update: Allows updates only if the data has only 'name' and 'age' fields with the same checks.
allow delete: Prevents deleting user documents.
firebase deploy --only firestore:rules
--only firestore:rules - Deploys only Firestore rules without affecting other Firebase services.firebase emulators:start --only firestore
--only firestore - Starts only the Firestore emulator.firebase firestore:rules:test --rules firestore.rules --test-file test.json
If you remember nothing else from this pattern, remember: data validation rules check data before saving to keep your database safe and clean.
Practice
Solution
Step 1: Understand what data validation means
Data validation checks if data meets certain conditions before saving.Step 2: Identify the role of Firebase rules
Firebase rules check data type, format, and permissions to keep data safe and clean.Final Answer:
To ensure data is correct and secure before saving -> Option AQuick Check:
Data validation = correctness and security [OK]
- Thinking rules speed up queries
- Confusing validation with UI creation
- Assuming rules backup data
name in Firebase rules?Solution
Step 1: Identify the method to check string type
Firebase usesnewData.isString()to check if data is a string.Step 2: Match the syntax with the correct method
"name": { ".validate": "newData.isString()" } usesnewData.isString(), which is correct for string validation.Final Answer:
"name": { ".validate": "newData.isString()" } -> Option AQuick Check:
Check string type = newData.isString() [OK]
- Using isNumber() for strings
- Using exists() which only checks presence
- Using val() > 0 which is for numbers
{
"rules": {
"users": {
"$uid": {
".write": "$uid === auth.uid",
".validate": "newData.hasChildren(['name', 'age']) && newData.child('age').isNumber() && newData.child('age').val() >= 18"
}
}
}
}What happens if a user tries to write data with
age set to 16?Solution
Step 1: Analyze the validation condition for age
The rule requiresageto be a number and at least 18.Step 2: Check the given age value
The user tries to writeage = 16, which is less than 18, so validation fails.Final Answer:
Write is denied because age is less than 18 -> Option CQuick Check:
Age must be ≥ 18 = deny if 16 [OK]
- Ignoring the minimum age check
- Assuming any number is allowed
- Confusing write and validate rules
{
".validate": "newData.isString() && newData.val().matches('.*@example.com$')"
}But users with emails like 'user@exampleacom' are still allowed. What is the error?
Solution
Step 1: Review the regex pattern used
The pattern '.*@example.com$' treats '.' as any character, not a literal dot.Step 2: Correct the regex to escape the dot
It should be '.*@example\.com$' to match the literal '.com' ending.Final Answer:
The regex pattern is incorrect; it should escape the dot -> Option BQuick Check:
Escape dot in regex = \. [OK]
- Not escaping '.' in regex
- Thinking matches() is unsupported
- Confusing isString() with exists()
posts node where each post must have a title (string, max 100 chars) and tags (array of strings, max 5 tags). Which rule correctly enforces this?Solution
Step 1: Check the available Firebase validation functions
Firebase rules do not support JavaScript array methods likeevery()ortypeofinside rules.Step 2: Identify the valid checks
We can check iftagsis an array and its length, but cannot check each tag's type in rules.Final Answer:
"posts": { "$postid": { ".validate": "newData.hasChildren(['title', 'tags']) && newData.child('title').isString() && newData.child('title').val().length() <= 100 && newData.child('tags').numChildren() <= 5" } } -> Option DQuick Check:
Use only supported rule functions, no JS methods [OK]
- Using JavaScript methods inside rules
- Trying to check each array element's type
- Assuming isArray() checks element types
Ready to prove it?
Pass the test and this pattern moves unknown
