In this tutorial, we will be learning about setting up data validation in Firebase. We'll define validation rules to ensure the data being sent to our database meets certain criteria.
By the end of this tutorial, you will be able to:
Prerequisites:
Data validation is a crucial part of any application. It ensures that only valid data gets stored in your database. In Firebase, we use security rules to validate data.
Firebase Security Rules:
Firebase Security Rules stand between your data and malicious users. They can validate the shape and size of your data, as well as authenticate users.
Setting Up Validation Rules:
In Firebase, you can write security rules in the Firebase console, under the 'Rules' tab of the Database section. You can also write and deploy them from the Firebase CLI.
Here's a basic example of what a Firebase rule looks like:
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
This rule ensures that only authenticated users can read or write data.
Best Practices:
Example 1:
Validating the structure of a document in Firestore:
{
"rules": {
"users": {
"$uid": {
".read": "auth != null && auth.uid == $uid",
".write": "auth != null && auth.uid == $uid",
"name": { ".validate": "newData.isString()" },
"age": { ".validate": "newData.isNumber() && newData.val() >= 18" }
}
}
}
}
In this example, we are validating that the name
field is a string and the age
field is a number greater than or equal to 18.
Example 2:
Limiting the size of a document or field in Firestore:
{
"rules": {
"posts": {
"$postId": {
".write": "auth != null",
".validate": "newData.hasChildren(['title', 'body']) && newData.child('body').isString() && newData.child('body').val().length <= 500"
}
}
}
}
In this example, we are ensuring that a post has a title
and a body
, and that the body
does not exceed 500 characters.
In this tutorial, we learned about data validation and how to set up validation rules in Firebase. Firebase security rules are versatile and powerful, allowing us to perform complex validations.
To further your learning, you can:
Exercise 1:
Write a validation rule that allows a user to write to their own profile, but not to others.
Solution:
{
"rules": {
"users": {
"$uid": {
".write": "auth != null && auth.uid == $uid"
}
}
}
}
Exercise 2:
Write a validation rule that ensures a post
document has a title
, body
, and authorId
, and that the title
does not exceed 100 characters.
Solution:
{
"rules": {
"posts": {
"$postId": {
".write": "auth != null",
".validate": "newData.hasChildren(['title', 'body', 'authorId']) && newData.child('title').isString() && newData.child('title').val().length <= 100"
}
}
}
}
Try creating more complex validation rules, such as ones that involve multiple fields or more complex data types.