2

Completely new to firebase, I want to set a phone number as the primary key (uid) and email as the secondary key. How can I prevent duplication of these two if they exist in my firebase database? I don't have any authentication in my application. I'm doing this for a contact form to prevent duplication

Below is my JS code

 // Submit form
function submitForm(e){
  e.preventDefault();

  // Get values
  var name = getInputVal('name');
  var company = getInputVal('company');
  var email = getInputVal('email');
  var phone = getInputVal('phone');
  var message = getInputVal('message');

  // Save message
  saveMessage(name, company, email, phone, message);
}

// Function to get get form values
function getInputVal(id){
  return document.getElementById(id).value;
}

// Save message to firebase
function saveMessage(name, company, email, phone, message){
  var newMessageRef = messagesRef.push();
  newMessageRef.set({
    name: name,
    company:company,
    email:email,
    phone:phone,
    message:message
  });
}

And below is the rule which I have set in firebase

{

 "rules": {
    ".read": "false",
    ".write": true,
    "phone": {  // assuming this as primary key
      ".validate": "newData.isString() && 
        newData.val().length == 10 &&
        !root.child('phone').child(newData.val()).exists()"
    }
   }
 }

enter image description here

Sai Manoj
  • 3,809
  • 1
  • 14
  • 35
  • Simply use the number as key instead of a key generated with push(). This also ensures there are no duplicate numbers. But offcourse the better way would be to authenticate users and use their UID :) – André Kool May 07 '19 at 19:24
  • @AndréKool I'm trying to prevent duplication of both, the phone number and email id. So how can I set the rules in my firebase database? Can you please put that in the snippet for my better understanding. TIA – Sai Manoj May 07 '19 at 19:28

1 Answers1

0

i recommend not to use phone number as primary key. use it as unique value. it seems like you are using jquery.validate plugin so you can access remote and have a look into your database to validate duplicate number.. otherwise. in your script.. before your saveMessage function. call ajax to take a look into database. if the number is exist prevent submission of your form and alert a message that number is already exist.

remote access example available at jquery validation with ajax call

Masih Ansari
  • 467
  • 3
  • 9