简体   繁体   中英

How to check email exists in firebase?

Hi I'm using firebase and javascript. I need to check for email id existing or not when new user signs up. This code works for user name or id, but shows error having email as record. I don't want to overwrite firebase unique key generation for each record.

var ref = new Firebase("https://kkk.firebaseio.com/");
var users = ref.child("users");
var userId = document.getElementById("email").value;
function checking()
{
   checkIfUserExists(userId);
}  
function userExistsCallback(userId, exists) {
  if (exists) {
    alert('user ' + userId + ' exists!');
  } else {
    alert('user ' + userId + ' does not exist!');
    var check = users.push({ email: username});
  }
}

function checkIfUserExists(userId) {

  users.child(userId).once('value', function(snapshot) {
    var exists = (snapshot.val() !== null);
    userExistsCallback(userId, exists);
  });
}

I'm getting this error when I enter email.

Error: Firebase.child failed: First argument was an invalid path: "anu@gmail.com". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"

I want my data in firebase to looks like this,

users:{
       "ksjhfsjkbv67dsjhbcxcscdg":{
          "email": "sdfs@gmail.com"
       },
       "kXdhbrurjw9974jjdsos_asd":{
          "email": "anu@gmail.com"
       },
       ...

Can someone help me?

If you're data in firebase has unique keys then it probably looks something like:

{
    users:{
       "dsjhfsjkbv67dsjhbcxcscdg":{
          "email": "blah@whatever.com"
       },
       "sXdhbrurjw9974jjdsos_asd":{
          "email": "anu@gmail.com"
       },
       ...
}

}

the error your getting is because you cannot have illegal characters as the "keys" for your data so:

{
    "anu@gmail.com": "email"
}

would not be acceptable hence the error:

Error: Firebase.child failed: First argument was an invalid path: "anu@gmail.com". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"

the "." is not allowed.

One way to check if your value exists if you do not know the unique key is to do something like:

users.once('value', function(snapshot) {
    var exists = false;
    snapshot.forEach(function(childSnapshot){
        if(userId === childSnapshot.val().email){
            exists = true;     
        }
    })
    userExistsCallback(userId, exists);
});

you can read more about the for each function here:

https://www.firebase.com/docs/web/api/datasnapshot/foreach.html

我认为您不必检查电子邮件是否已经有帐户,因为 firebase 无法使用相同的电子邮件创建另一个帐户。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM