Bird
Raised Fist0
Firebasecloud~5 mins

Data validation rules in Firebase - Commands & Configuration

Choose your learning style10 modes available
Introduction
Data validation rules in Firebase help make sure the information saved in your database is correct and safe. They check data before saving it, so mistakes or bad data don't get stored.
When you want to make sure users only save data in the right format, like numbers or text.
When you want to prevent users from deleting or changing data they shouldn't.
When you want to check that required fields are not empty before saving.
When you want to limit the size or length of data, like text length or number range.
When you want to control who can read or write certain parts of your database.
Config File - firestore.rules
firestore.rules
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.

Commands
This command uploads and activates the Firestore security rules defined in the 'firestore.rules' file to your Firebase project.
Terminal
firebase deploy --only firestore:rules
Expected OutputExpected
=== Deploying to 'your-project-id'... i deploying firestore i firestore: releasing rules... ✔ firestore: rules released successfully ✔ Deploy complete!
→
--only firestore:rules - Deploys only Firestore rules without affecting other Firebase services.
Starts the local Firestore emulator to test your rules and database behavior without affecting the live database.
Terminal
firebase emulators:start --only firestore
Expected OutputExpected
i emulators: Starting emulators: firestore ✔ firestore emulator running at http://localhost:8080 All emulators started, it is now safe to connect.
→
--only firestore - Starts only the Firestore emulator.
Runs tests against your Firestore rules using a test file to check if your validation rules work as expected.
Terminal
firebase firestore:rules:test --rules firestore.rules --test-file test.json
Expected OutputExpected
Running Firestore rules tests... All tests passed successfully.
Key Concept

If you remember nothing else from this pattern, remember: data validation rules check data before saving to keep your database safe and clean.

Common Mistakes
Allowing write access without checking user identity.
This lets anyone change any data, risking security and data corruption.
Always check that the user is authenticated and only allowed to write their own data.
Not validating data types or required fields.
Bad or incomplete data can cause app errors or wrong behavior.
Use rules to check data types and required fields before allowing writes.
Allowing delete operations without restrictions.
Users might delete important data accidentally or maliciously.
Restrict delete permissions or disable them if not needed.
Summary
Write Firestore rules in 'firestore.rules' to validate data before saving.
Deploy rules using 'firebase deploy --only firestore:rules' to activate them.
Test rules locally with Firebase emulators to avoid affecting live data.

Practice

(1/5)
1. What is the main purpose of Firebase data validation rules?
easy
A. To ensure data is correct and secure before saving
B. To speed up database queries
C. To create user interfaces automatically
D. To backup data to another server

Solution

  1. Step 1: Understand what data validation means

    Data validation checks if data meets certain conditions before saving.
  2. Step 2: Identify the role of Firebase rules

    Firebase rules check data type, format, and permissions to keep data safe and clean.
  3. Final Answer:

    To ensure data is correct and secure before saving -> Option A
  4. Quick Check:

    Data validation = correctness and security [OK]
Hint: Validation means checking data before saving [OK]
Common Mistakes:
  • Thinking rules speed up queries
  • Confusing validation with UI creation
  • Assuming rules backup data
2. Which of the following is the correct syntax to allow only string data for a field name in Firebase rules?
easy
A. "name": { ".validate": "newData.isString()" }
B. "name": { ".validate": "newData.isNumber()" }
C. "name": { ".validate": "newData.exists()" }
D. "name": { ".validate": "newData.val() > 0" }

Solution

  1. Step 1: Identify the method to check string type

    Firebase uses newData.isString() to check if data is a string.
  2. Step 2: Match the syntax with the correct method

    "name": { ".validate": "newData.isString()" } uses newData.isString(), which is correct for string validation.
  3. Final Answer:

    "name": { ".validate": "newData.isString()" } -> Option A
  4. Quick Check:

    Check string type = newData.isString() [OK]
Hint: Use newData.isString() to validate strings [OK]
Common Mistakes:
  • Using isNumber() for strings
  • Using exists() which only checks presence
  • Using val() > 0 which is for numbers
3. Given this Firebase rule snippet:
{
  "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?
medium
A. Write is denied because name is missing
B. Write is allowed because age is a number
C. Write is denied because age is less than 18
D. Write is allowed regardless of age

Solution

  1. Step 1: Analyze the validation condition for age

    The rule requires age to be a number and at least 18.
  2. Step 2: Check the given age value

    The user tries to write age = 16, which is less than 18, so validation fails.
  3. Final Answer:

    Write is denied because age is less than 18 -> Option C
  4. Quick Check:

    Age must be ≥ 18 = deny if 16 [OK]
Hint: Check numeric conditions carefully in validation [OK]
Common Mistakes:
  • Ignoring the minimum age check
  • Assuming any number is allowed
  • Confusing write and validate rules
4. You wrote this Firebase rule to allow only emails ending with '@example.com':
{
  ".validate": "newData.isString() && newData.val().matches('.*@example.com$')"
}

But users with emails like 'user@exampleacom' are still allowed. What is the error?
medium
A. matches() does not work in Firebase rules
B. The regex pattern is incorrect; it should escape the dot
C. newData.isString() is missing
D. The rule should use newData.exists() instead

Solution

  1. Step 1: Review the regex pattern used

    The pattern '.*@example.com$' treats '.' as any character, not a literal dot.
  2. Step 2: Correct the regex to escape the dot

    It should be '.*@example\.com$' to match the literal '.com' ending.
  3. Final Answer:

    The regex pattern is incorrect; it should escape the dot -> Option B
  4. Quick Check:

    Escape dot in regex = \. [OK]
Hint: Escape dots in regex with double backslash \ [OK]
Common Mistakes:
  • Not escaping '.' in regex
  • Thinking matches() is unsupported
  • Confusing isString() with exists()
5. You want to write a Firebase validation rule for a 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?
hard
A. "posts": { "$postid": { ".validate": "newData.hasChildren(['title', 'tags']) && newData.child('title').isString() && newData.child('title').val().length() <= 100 && newData.child('tags').numChildren() <= 5 && newData.child('tags').val().every(tag => typeof tag === 'string')" } }
B. "posts": { "$postid": { ".validate": "newData.hasChildren(['title', 'tags']) && newData.child('title').isString() && newData.child('title').val().length() <= 100 && newData.child('tags').numChildren() <= 5 && newData.child('tags').val().forEach(tag => typeof tag === 'string')" } }
C. "posts": { "$postid": { ".validate": "newData.hasChildren(['title', 'tags']) && newData.child('title').isString() && newData.child('title').val().length() <= 100 && newData.child('tags').numChildren() <= 5 && newData.child('tags').val().every(tag => tag.isString())" } }
D. "posts": { "$postid": { ".validate": "newData.hasChildren(['title', 'tags']) && newData.child('title').isString() && newData.child('title').val().length() <= 100 && newData.child('tags').numChildren() <= 5" } }

Solution

  1. Step 1: Check the available Firebase validation functions

    Firebase rules do not support JavaScript array methods like every() or typeof inside rules.
  2. Step 2: Identify the valid checks

    We can check if tags is an array and its length, but cannot check each tag's type in rules.
  3. 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 D
  4. Quick Check:

    Use only supported rule functions, no JS methods [OK]
Hint: Firebase rules don't support JS array methods like every() [OK]
Common Mistakes:
  • Using JavaScript methods inside rules
  • Trying to check each array element's type
  • Assuming isArray() checks element types
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard