如何检查 JS 中缺少的变量?

How to Check for a missing variable In JS?

我试图在允许提交表单之前检查变量是否存在。

目前,用户在表单中输入地址,自动完成功能会在表单中添加纬度和经度。我写了下面的js

function check() {
    let latitude = document.getElementById("latitude").value;
    if (latitude == null) {
        window.prompt("ned a correct address", "");
        return false;
    } else {
        alert('It worked');
        return true;
    }
}

当我提交一个没有经纬度自动完成的地址时,我仍然得到 "it worked"

这是我的表格

<form method="GET" action="/search" onsubmit="check()">
    <input class="form-control" id="getaddy" type="text" placeholder="Search..." name="term" onFocus="geo()">
    <input id="latitude" type="hidden" name="latitude">
    <input id="longitude" type="hidden" name="longitude">
</form>

为了更可靠的表单验证,这里需要考虑一些事项;

  1. 建议在验证失败时使用事件对象取消提交操作
  2. 通过测试 "empty string" 而不是 null
  3. 来验证输入字段值
  4. 确保您的脚本中没有错误(即确保 geo() 已定义等),以便 check() 实际被调用而不是由于另一个脚本错误而静默地失败

以下更改可能会有所帮助:

// Pass event object
function check(event) {
  
  let address = document.getElementById("getaddy").value;
  
  // Check for empty string, rather than null
  if (address === '') { 
    window.prompt("ned a correct address", "");
      
    // Use Event#preventDefault() to prevent submit
    // as a more reliable alternative to returning 
    // false
    event.preventDefault();
  } else {
  
    alert('It worked');
  }
}


// Ensure geo() is defined, seeing your form is relying on this
function geo() { }
<!-- update check call to pass event object -->
<form method="GET" action="/search" onsubmit="check(event)">

  <input class="form-control" id="getaddy" type="text" placeholder="Search..." name="term" onFocus="geo()">
  <input id="latitude" type="hidden" name="latitude">
  <input id="longitude" type="hidden" name="longitude">
  
</form>

如果你真的想检查一个变量是否存在,有一个安全的方法,使用:

if(variable) {
  // Truthy
} else {
  // Falsy
}

这样,您将获得所有可能的 Falsy 场景,包括:nullundefinedNaN""0最后 false 本身......没有检查每一个!

这是编辑后的片段:

function check() {
  let latitude = document.getElementById("latitude").value;
  if (latitude) {
    alert('It worked');
    return true;
  } else {
    window.prompt("ned a correct address", "");
    return false;
  }
}
<form method="GET" action="/search" onsubmit="check()">
  <input class="form-control" id="getaddy" type="text" placeholder="Search..." name="term" onFocus="geo()">
  <input id="latitude" type="hidden" name="latitude">
  <input id="longitude" type="hidden" name="longitude">
</form>

*这段代码只会执行一次!