0Pricing
Firebase Auth & Realtime Database Apps · Aula

Validando dados com regras

Use regras de segurança para validar os dados recebidos, garantindo que estejam nos formatos esperados e evitando gravações maliciosas.

Validando dados com regras é uma aula grátis de Firebase Auth & Realtime Database Apps no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Firebase Auth & Realtime Database Apps, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Firebase Auth & Realtime Database Apps inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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!

Perguntas Frequentes

A aula “Validando dados com regras” é grátis?

Sim — o texto completo de “Validando dados com regras” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Firebase Auth & Realtime Database Apps, atualize para CoddyKit PRO. O curso de Firebase Auth & Realtime Database Apps inclui 4 aulas no total.

O que vou aprender em “Validando dados com regras”?

Use regras de segurança para validar os dados recebidos, garantindo que estejam nos formatos esperados e evitando gravações maliciosas. Você pratica Firebase Auth & Realtime Database Apps com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Firebase Auth & Realtime Database Apps?

Nenhuma experiência prévia é necessária. Firebase Auth & Realtime Database Apps no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.

Quanto tempo leva a aula “Validando dados com regras”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Firebase Auth & Realtime Database Apps?

Sim. Cada aula de Firebase Auth & Realtime Database Apps inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Compreendendo a sintaxe das regras de segurança
  2. Controle de acesso baseado no usuário
  3. Validando dados com regras
  4. Testes e Depuração de Regras de Segurança
← Voltar para Firebase Auth & Realtime Database Apps