0
0
Firebasecloud~30 mins

Data validation rules in Firebase - Mini Project: Build & Apply

Choose your learning style9 modes available
Firebase Data Validation Rules
📖 Scenario: You are building a simple Firebase Realtime Database to store user profiles. Each user has a unique ID, a name, and an age. You want to make sure that the data entered is correct and safe by using Firebase data validation rules.
🎯 Goal: Create Firebase Realtime Database validation rules that allow only user profiles with a name as a non-empty string and an age as a number between 1 and 120. Also, ensure that the user ID is a valid key.
📋 What You'll Learn
Create a users node in the database
Add a validation rule to check that name is a string and not empty
Add a validation rule to check that age is a number between 1 and 120
Ensure the user ID key is a valid Firebase key
💡 Why This Matters
🌍 Real World
Firebase data validation rules protect your database from bad or malicious data by enforcing correct data formats and values.
💼 Career
Understanding Firebase rules is essential for backend and full-stack developers working with Firebase to ensure data integrity and security.
Progress0 / 4 steps
1
Create the users node structure
Create a Firebase Realtime Database rules object with a users node that allows read and write access for now.
Firebase
Need a hint?

Start by allowing all reads and writes on the users node.

2
Add validation for name field
Inside the users node, add a $userId wildcard and create a name child validation rule that checks if newData.isString() and newData.val().length > 0.
Firebase
Need a hint?

Use $userId as a wildcard for user keys and validate the name field inside it.

3
Add validation for age field
Inside the $userId node, add an age child validation rule that checks if newData.isNumber() and newData.val() >= 1 and newData.val() <= 120.
Firebase
Need a hint?

Validate that age is a number between 1 and 120 inclusive.

4
Validate the $userId key format
Add a validation rule on the $userId wildcard to ensure the key matches the regex ^[a-zA-Z0-9_-]+$ using newData.exists() and newData.key.matches().
Firebase
Need a hint?

Use newData.key.matches() to check the user ID format.