1

Recently found out the database rules can be set to validate whether the database already have the same data but currently it just accepted same data to insert but how to validate and prevent same input of username and email?

{
"rules": {
        ".read": true,
    ".write": true,
        "username":{
       ".validate": "!root.child('username').child(newData.val()).exists()"
        },
        "email":{
        ".validate": "!root.child('email').child(newData.val()).exists()"
      }

        }
  }

The root child is created by email authentication uid and the rest will be under the same nodes.

enter image description here

How to prevent user enter same username and email?

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
Cracker Rex
  • 91
  • 14

1 Answers1

1

Your rules validate if a single property /username exists and has the same value as the new data you're writing. Your use-case seems different: you want to ensure a unique user name across all users.

You cannot ensure a unique value across many multiple nodes in Firebase's security rules. You instead will need to store the user names as keys in a separate collection, i.e.

usernames
  "rexyou0831": "ik3sf...."

The above data structure indicates that user ik3sf... claimed name rexyou0831. With such a structure in place, user names are guaranteed to be unique since keys must by definition be unique in a collection. You can ensure that users can only write new names or delete their own name with:

{
  "rules": {
    "usernames": {
      "$name": {
        ".write": "!data.exists() || newData.val() === data.val()"
      }
    }
  }
}

To enforce uniqueness of the email addresses too, you will need to create a similar collection for those.

For more explanation read one of the previous questions covering this same topic:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807