使用规则验证数据
使用安全规则验证传入数据,确保其符合预期格式并防止恶意写入
使用规则验证数据 是 CoddyKit 上的免费 Firebase Auth & Realtime Database Apps 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Firebase Auth & Realtime Database Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Firebase Auth & Realtime Database Apps 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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
newDataobject represents data being written. - The
.validate()rule enforces conditions onnewData. - 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!
常见问题解答
「使用规则验证数据」课时是免费的吗?
是的 — 「使用规则验证数据」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Firebase Auth & Realtime Database Apps 课程的其余内容,请升级到 CoddyKit PRO。 Firebase Auth & Realtime Database Apps 课程共包含 4 节课。
「使用规则验证数据」这节课中我会学到什么?
使用安全规则验证传入数据,确保其符合预期格式并防止恶意写入 你通过在浏览器中直接运行的动手代码来练习 Firebase Auth & Realtime Database Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Firebase Auth & Realtime Database Apps 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Firebase Auth & Realtime Database Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「使用规则验证数据」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Firebase Auth & Realtime Database Apps 课中编写并运行代码吗?
能。每节 Firebase Auth & Realtime Database Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。