0Pricing
Firebase Auth & Realtime Database Apps · Lekcja

Walidacja danych za pomocą reguł

Używaj reguł bezpieczeństwa do walidowania przychodzących danych, upewniając się, że mają oczekiwany format i nie umożliwiają złośliwych zapisów.

Walidacja danych za pomocą reguł to bezpłatna lekcja Firebase Auth & Realtime Database Apps na CoddyKit. To lekcja 3 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Firebase Auth & Realtime Database Apps, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Firebase Auth & Realtime Database Apps zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

Why Validate Data?

Welcome to Lesson 3! In this lesson, we'll learn how to use Firebase Realtime Database Security Rules to validate incoming data. This is super important to:

  • Prevent bad or malicious data from entering your database.
  • Maintain the integrity and consistency of your application's data.
  • Ensure data conforms to expected formats and types.

Think of it as a bouncer for your database!

Introducing newData & .validate()

When data is written to your database, Firebase provides a special object called newData. This object represents the data that's about to be written.

We use the .validate() rule to define conditions that newData must meet. If these conditions aren't met, the write operation will be rejected.

Here's a basic example:

{
  "rules": {
    "posts": {
      "$postId": {
        // Allow anyone authenticated to write
        ".write": "auth != null",
        // Validate that new posts must have 'title' and 'content'
        ".validate": "newData.hasChildren(['title', 'content'])"
      }
    }
  }
}

Checking Data Types

One of the most common validations is checking the data type. You can ensure fields are strings, numbers, booleans, or even null.

This helps prevent users from submitting, for example, a number where a name (string) is expected.

{
  "rules": {
    "users": {
      "$userId": {
        "name": { ".validate": "newData.isString()" },
        "age": { ".validate": "newData.isNumber()" },
        "isActive": { ".validate": "newData.isBoolean()" }
      }
    }
  }
}

Making Fields Mandatory

Sometimes, certain fields are absolutely required. You can use newData.hasChildren(['field1', 'field2']) to ensure multiple fields exist, or directly access a child to check its presence.

If a required field is missing, the write will fail.

{
  "rules": {
    "messages": {
      "$messageId": {
        ".validate": "newData.hasChildren(['senderId', 'text'])"
      }
    }
  }
}

Controlling String Lengths

For text fields, you often want to limit the minimum or maximum length. This prevents overly short or excessively long inputs.

You can use the .length property on a string value.

{
  "rules": {
    "products": {
      "$productId": {
        "name": {
          ".validate": "newData.isString() && newData.val().length > 2 && newData.val().length < 50"
        }
      }
    }
  }
}

Setting Number Ranges

For numerical data, you might need to ensure values fall within a specific range. For example, an age must be positive, or a score must be between 0 and 100.

You can use standard comparison operators (>, <, >=, <=).

{
  "rules": {
    "scores": {
      "$scoreId": {
        "value": {
          ".validate": "newData.isNumber() && newData.val() >= 0 && newData.val() <= 100"
        }
      }
    }
  }
}

Advanced Pattern Matching

For more complex string formats, like emails or URLs, you can use regular expressions with the .matches() function.

Regular expressions are powerful patterns for matching text. They can seem intimidating at first, but are very useful!

{
  "rules": {
    "profiles": {
      "$profileId": {
        "email": {
          // Basic email regex pattern validation
          ".validate": "newData.isString() && newData.val().matches(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$/i)"
        }
      }
    }
  }
}

Combining Validation Rules

You'll often need to combine multiple validation checks. You can use logical operators:

  • && (AND): All conditions must be true.
  • || (OR): At least one condition must be true.

This allows for very flexible and robust validation logic.

{
  "rules": {
    "tasks": {
      "$taskId": {
        ".validate": "newData.hasChildren(['title', 'status']) && newData.child('title').isString() && newData.child('title').val().length > 5"
      }
    }
  }
}

User Profile Validation Example

Let's put it all together with a comprehensive example for a user profile:

  • username: must be a string, at least 3 characters.
  • email: must be a string and match an email regex.
  • age: must be a number and at least 13.
{
  "rules": {
    "userProfiles": {
      "$userId": {
        ".validate": "newData.hasChildren(['username', 'email', 'age']) && \
                      newData.child('username').isString() && \
                      newData.child('username').val().length >= 3 && \
                      newData.child('email').isString() && \
                      newData.child('email').val().matches(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$/i) && \
                      newData.child('age').isNumber() && \
                      newData.child('age').val() >= 13"
      }
    }
  }
}

Validate Your Knowledge

Consider a rule for a 'product' node. A product must have a 'name' (string, min 2 chars, max 100 chars) and a 'price' (number, greater than 0).

Recap: Data Integrity Secured

Great job! You've learned how to use Firebase Realtime Database Security Rules to validate data:

  • The newData object represents data being written.
  • The .validate() rule enforces conditions on newData.
  • You can check data types (isString(), isNumber()).
  • Ensure required fields exist with hasChildren().
  • Validate string lengths (.length) and number ranges (>, <).
  • Use .matches() for complex pattern validation with regex.
  • Combine rules with && and || for powerful logic.

By validating data, you ensure your database remains clean and secure!

Często zadawane pytania

Czy lekcja „Walidacja danych za pomocą reguł” jest bezpłatna?

Tak — pełny tekst „Walidacja danych za pomocą reguł” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Firebase Auth & Realtime Database Apps, przejdź na CoddyKit PRO. Kurs Firebase Auth & Realtime Database Apps zawiera 4 lekcji w sumie.

Co nauczysz się w „Walidacja danych za pomocą reguł”?

Używaj reguł bezpieczeństwa do walidowania przychodzących danych, upewniając się, że mają oczekiwany format i nie umożliwiają złośliwych zapisów. Ćwiczysz Firebase Auth & Realtime Database Apps z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Firebase Auth & Realtime Database Apps?

Nie wymagamy żadnego doświadczenia. Firebase Auth & Realtime Database Apps w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 3 z 4.

Ile czasu zajmuje lekcja „Walidacja danych za pomocą reguł”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Firebase Auth & Realtime Database Apps?

Tak. Każda lekcja Firebase Auth & Realtime Database Apps zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Zrozumienie składni reguł bezpieczeństwa
  2. Kontrola dostępu oparta na użytkownikach
  3. Walidacja danych za pomocą reguł
  4. Testowanie i debugowanie reguł bezpieczeństwa
← Powrót do Firebase Auth & Realtime Database Apps