我试图防止电子邮件 ID 和电话号码重复,因此在提交表单后我首先检查数据库中的电子邮件 ID 和电话号码。如果其中任何一个存在,它应该显示错误消息 email already exists in the database
否则它应该将数据推送到 firebase 实时数据库。我的申请在第一次提交表格时工作正常。如果我第二次提交具有新值的表单,数据将被添加两次。如果我第 3 次提交具有新值的表单,这些值将被提交 3 次并被推送到我的 firebase 数据库中,甚至它会抛出错误消息。它从第二次提交具有新值的表单开始进入 if 和 else 条件。任何修复,请帮助我。
下面是我试过的代码
firebase.initializeApp(firebaseConfig);
// Listen for form submit
document.getElementById('contactform1').addEventListener('submit', submitForm);
// Submit form
function submitForm(e) {
e.preventDefault();
// Get values
var fname = getInputVal('fname');
var lname = getInputVal('lname');
var newEmail = getInputVal('email');
var newPhone = getInputVal('phone');
var newskills = getInputVal('skills');
var newjobId = getInputVal('jid');
var newlinkedin = getInputVal('linkedin');
var newgithub = getInputVal('github');
var newlocation = getInputVal('location');
saveMessage(fname, lname, newEmail, newskills, newPhone, newjobId, newlinkedin, newgithub, newlocation);
}
function saveMessage(fname, lname, newEmail, skills, newPhone, jobId, linkedin, github, location) {
let ref = firebase.database().ref().child('self/data/');
ref.once('value', snap => {
if (snap.exists()) {
snap.forEach(childSnapshot => {
var email = childSnapshot.child('email').val();
var phone = childSnapshot.child('phone').val();
console.log(status);
if (newEmail.trim() === email.trim() || newPhone.trim() === phone.trim()) { //check if email exists
console.log("email already exists in the database");
} else {
console.log('hello');
firebase.database().ref().child('self/data/').push().set({
name: fname + " " + lname,
email: email,
phone: phone,
skills: skills,
jobId: jobId,
linkedin: linkedin,
github: github,
location: location
});
}
});
} else {
firebase.database().ref().child('self/data/').push().set({
name: fname + " " + lname,
email: email,
phone: phone,
skills: skills,
jobId: jobId,
linkedin: linkedin,
github: github,
location: location
});
}
});
}
// Function to get get form values
function getInputVal(id) {
return document.getElementById(id).value;
}
最佳答案
是的,循环内部似乎存在逻辑问题,请尝试这种方式:
function saveMessage(fname, lname, newEmail, skills, newPhone, jobId, linkedin, github, location) {
let ref = firebase.database().ref().child('self/data/');
ref.once('value', snap => {
let isDuplicated = false;
if (snap.exists()) {
snap.forEach(childSnapshot => {
var email = childSnapshot.child('email').val();
var phone = childSnapshot.child('phone').val();
console.log(status);
if (newEmail.trim() === email.trim() || newPhone.trim() === phone.trim()) { //check if email exists
isDuplicated = true;
}
});
}
if (snap.exists() && !isDuplicated) {
firebase.database().ref().child('self/data/').push().set({
name: fname + " " + lname,
email: email,
phone: phone,
skills: skills,
jobId: jobId,
linkedin: linkedin,
github: github,
location: location
});
}
});
}
关于javascript - 提交表单并使用快照检索数据后,防止在未经身份验证的情况下在 Firebase 应用程序中重复邮件 ID 和电话号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56438150/