0

I'm completely new to firebase. I'm creating a basic contact form for my application and connected that to the firebase database. I don't have any authentication for my application. . I have set all the rules to True . I want to prevent duplication, if there exists email in database I want to display an error message.

Below is my code which I have tried

var config = {
  apiKey: "AIzaSyDA3u4bIIYHHTcB8u11NxtRVh9MOWe0jJQ",
  authDomain: "wable-bb8b1.firebaseapp.com",
  databaseURL: "https://wable-bb8b1-default-rtdb.firebaseio.com",
  projectId: "wable-bb8b1",
  storageBucket: "wable-bb8b1.appspot.com",
  messagingSenderId: "739938703423",
};
firebase.initializeApp(config);


// Reference messages collection
var messagesRef = firebase.database().ref('Email');

// Listen for form submit
document.getElementById('contactForm').addEventListener('submit', submitForm);


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

  //Get value
  var email = getInputVal('email');

  // Save message
  saveMessage(email);

  // Show alert
  document.querySelector('.alert').style.display = 'block';

  // Hide alert after 3 seconds
  setTimeout(function(){
    document.querySelector('.alert').style.display = 'none';
  },3000);

  // Clear form
  document.getElementById('contactForm').reset();
}

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

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

I looked for some solutions but it didn't work

Frank van Puffelen
  • 499,950
  • 69
  • 739
  • 734
  • If you want to prevent duplicate of some property in Firebase's Realtime Database, you need to store those properties as the **keys** under a node. Because keys are by definition unique, this solves the entire problem. Now email addresses contain a `.` which is not allowed in Firebase Realtime Database, so the common workaround is to replace those with a `,` in the keys (since `,` is conveniently not allowed in an email address). I linked a few relevant previous questions to yours. – Frank van Puffelen Sep 11 '21 at 15:11

0 Answers0