javascript - 使用 if 检查函数的条件是真还是假
问题描述
下面的代码是函数检查,它是一个条件函数,其中函数 save_user() 必须执行,只有这些条件都满足
function check(){
var myInput = document.getElementById("user_name2");
var letter = document.getElementById("letter");
var number = document.getElementById("number");
var length = document.getElementById("length");
// When the user clicks on the password field, show the message box
myInput.onfocus = function() {
document.getElementById("message").style.display = "block";
}
// When the user clicks outside of the password field, hide the message box
myInput.onblur = function() {
document.getElementById("message").style.display = "none";
}
// When the user starts to type something inside the password field
myInput.onkeyup = function() {
// Validate lowercase letters
var lowerCaseLetters = /[a-z]/g;
if(myInput.value.match(lowerCaseLetters)) {
letter.classList.remove("invalid");
letter.classList.add("valid");
} else {
letter.classList.remove("valid");
letter.classList.add("invalid");
}
// Validate numbers
var numbers = /[0-9]/g;
if(myInput.value.match(numbers)) {
number.classList.remove("invalid");
number.classList.add("valid");
} else {
number.classList.remove("valid");
number.classList.add("invalid");
}
// Validate length
if(myInput.value.length >= 4) {
length.classList.remove("invalid");
length.classList.add("valid");
} else {
length.classList.remove("valid");
length.classList.add("invalid");
}
}
}
下面的代码是执行函数,它应该只在满足函数 check() 条件时才更新数据库
function save_user(){
var user_name = document.getElementById('user_name').value;
var user_name2 = document.getElementById('user_name2').value;
uid = firebase.database().ref().child('users').push().key;
var data = {
user_id: uid,
user_name: user_name,
password: user_name2
}
var updates = {};
updates['/users/' + uid] = data;
if(check)
{
firebase.database().ref().update(updates);
alert('The user is created successfully!');
reload_page();
document.writeln(uid);
}
else{
alert('not satisfied');
}
}
此代码的预期输出是只有当至少有 4 个字符、1 个小写字母和至少 1 个数值时,才应将值更新到数据库中 这些条件在函数 check() 中指定并在函数 save_user() 中调用,如
if(check)
如果条件不满足应该弹出不满足
解决方案
你的check()
函数没有返回值,所以它总是false
并且if(check)
正在检查变量而不是函数,您可以将其更改为,if(check())
但它始终会false
因为check()
函数不返回值
尝试将其添加到函数的末尾:
return ( length.classList.contains("valid") && number.classList.contains("valid") && letter.classList.contains("valid") )
推荐阅读
- python - Python代码运行缓慢
- python - 如何解决六边形图中的边缘问题?
- spring - 考虑在你的配置中定义一个 'org.springframework.social.twitter.api.Twitter' 类型的 bean
- html - 粘性标题和表格组合打破了流程
- azure-cosmosdb - Cosmos DB 对数据库的分区访问
- javascript - 引导模式在 Chrome 中不起作用
- c# - 具有多个具有不同过滤条件的观察者的可观察集合
- c++ - c++ 函数的可选写出参数
- php - php mysql UNION ALL - 从单独的表中获取 id
- javascript - Webdriver.io 在尝试创建新会话时从 selenium 获得 HTML 响应