点击事件的Javascript关闭问题

时间:2017-07-21 12:38:37

标签: javascript json validation scope closures

我已经查看了"关闭"的许多答案。问题,但无法解决我的具体问题。

以下js代码获取一个json文件并存储它,然后根据数据进行一些表单验证。

问题在于提交表单和执行validate函数我应该看到两个错误,但我只得到最后一个字段的错误(在控制台中登录)。

这是一个明显的关闭问题但是我花了一整天时间仍然无法修复它。下面是代码,点击事件位于底部...

我现在只检查最小长度规则。

// Get the json file and store
function loadJSON(callback) {
  var xobj = new XMLHttpRequest();
  xobj.overrideMimeType("application/json");
  xobj.open('GET', 'js/rules.json');
  xobj.onreadystatechange = function () {
    if (xobj.readyState == 4 && xobj.status == "200") {
      // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
      callback(xobj.responseText);
    }
  };
  xobj.send(null);
}

// Load json...
loadJSON(response);

// Create global vars...
var lookup = [], errors = [], i, e, id, lookupId, minLength;

function response(responseData) {
  // Create objects from json data
  var rulesSet = JSON.parse(responseData);

  // Loop through objects
  for (i = 0;  i < rulesSet.length; i++) {
    // Create a lookup for each object that can be used later
    lookup[rulesSet[i].id] = rulesSet[i];
  }

  // Loop through form elements and store id's

  // Validate the form
  function validate(e) {
    var elements = document.getElementsByTagName('input');
    for (e = 0; e < elements.length; e++) {
      id = elements[e].getAttribute('id');
      lookupId = lookup[id].rules; var rules;
      // Loop through rules of the matched ID's
      for (rules of lookupId){
        // Check if there is a min length rule
        if(rules.name === 'min_length') {
          minLength = rules.value.toString();
          // Check if the rule is valid (is a number)
          if(isNaN(minLength) || minLength.length === 0){
            // Log an error somewhere here
          // Run the minLength function and report an error if it fails validation
          } else if(!checkMinLength(minLength, id)) {
            errors[errors.length] = id + " - You must enter more than " + minLength + " characters";
          }
        }
      }
      // If there are errors, report them
      if (errors.length > 0) {
        reportErrors(errors);
        //e.preventDefault();
      }
    }
  }
  validate();

  // Check the length of the field
  function checkMinLength(minLength, id){
    var val = document.getElementById(id).value;
    if(val < minLength){
      return false;
    }
    return true;
  }

  // Error reporting
  function reportErrors(errors){
    for (var i=0; i<errors.length; i++) {
        var msg = errors[i];
    }
    console.log(msg);
  }

  $('#email-submit').on('click',function(e){
      validate(e);
  });

}

可能不相关,但下面是加载的json ......

[
  {
    "id": "search",
    "rules": [
      {
        "name": "min_length",
        "value": "5"
      },
      {
        "name": "email"
      }
    ]
  },
  {
    "id": "phone-number",
    "rules": [
      {
        "name": "min_length",
        "value": 8
      }
    ]
  },
  {
    "id": "surname",
    "rules": [
      {
        "name": "min_length",
        "value": 10
      }
    ]
  }
]

验证的基本形式......

<form action="index.html" name="searchForm" id="search-form">
            <label for="search">Email</label>
  <input type="text" id="search" name="email" placeholder="Enter email">
  <input type="text" id="phone-number" name="name" placeholder="Enter name">
        <button type="submit" id="email-submit">Submit</button>
    </form>

2 个答案:

答案 0 :(得分:0)

代码完全按照您的要求执行

// Error reporting
function reportErrors(errors){
  for (var i=0; i<errors.length; i++) {
    var msg = errors[i];  <-- setting the variable on each iteration
  }
  console.log(msg);  <-- reads the last value from the last iteration
}

您需要在for循环中移动控制台

// Error reporting
function reportErrors(errors){
  for (var i=0; i<errors.length; i++) {
    var msg = errors[i];  
    console.log(msg);  
  }
}

或甚至不循环

// Error reporting
function reportErrors(errors){
  console.log(errors.join("\n"));        
}

现在是一个逻辑问题,你在for循环中声明了一个函数

function response(responseData) {
  // ignored code //

  var elements = document.getElementsByTagName('input');
  for (e = 0; e < elements.length; e++) {
    function validate(e) {  <-- THIS SHOULD NOT BE IN THE FOR LOOP

再次就像错误信息一样,只有最后一个会在那里......

答案 1 :(得分:0)

创建更具可读性的方案,无需关闭。

var submitButton = document.querySelector('#email-submit')

function validate (evt) {
  async function loadRules (url) {
    var rawData = await fetch(url)
    return await rawData.json()
  }

  function reportErrors (error) {
    evt.preventDefault()
    // Report logic here
  }

  function evaluate (rules) {
    // Your validate rules here
    // loaded rules in rules object
    // eg. rules[0]['rules'].name
  }

  loadRules('js/rules.json').then(evaluate)
}

submitButton.addEventLister('click', validate)