循环访问对象以查找输入名称

时间:2017-07-22 14:52:41

标签: javascript jquery

我有几个输入:

<input name="education[1][yearbegin]" type="date" class="form-control">
<input name="education[2][yearbegin]" type="date" class="form-control">

数据被发送到我的服务器进行验证,如果它无效,它会发送回数据:

{
    "education.0.institution":["The education.0.institution field is required."],
    "education.0.degree":["The education.0.degree field is required."]
}

我并不总是得到超过1回,有时可能会有很多我试图循环以向输入添加错误,如下所示:

var errors = $.parseJSON(data.responseText);
alertHtml += '<ul>';
$.each(errors, function (key, value) {
    $('.form-control[name=' + key + ']').closest('.form-group').addClass('has-error');
    alertHtml += '<li>' + value + '</li>';
});
alertHtml += "</ul>";

这不起作用,因为它试图找到输入名称:

education.1.yearbegin

而不是

education[1]yearbegin

我的输入并不总是排列,但是那些不附加的输入如何通过更改javascript将错误消息附加到输入? json由Laravel的阵列验证发送回来

3 个答案:

答案 0 :(得分:0)

很遗憾,服务器接受一种形式的名称,但将其发送回另一种形式。

如果我们假设点语法应始终转换为括号语法,则更新键非常简单:

var updated = key.split(".");
if (updated.length == 1) {
  updated = updated[0];
} else {
  updated = updated[0] + "[" + updated.slice(1).join("][") + "]";
}

对于多部分键,在第二个和{3}之间插入[,在第二个和第三个,第三个和第四个之间插入][等;并在最后添加]

示例:

&#13;
&#13;
var errors = [
  {"education.1.yearbegin":["The education.1.yearbegin field is required."]},
  {"education.2.yearbegin":["The education.2.yearbegin field is required."]}
];
errors.forEach(function(error) {
  Object.keys(error).forEach(function(key) {
    var updated = key.split(".");
    if (updated.length == 1) {
      updated = updated[0];
    } else {
      updated = updated[0] + "[" + updated.slice(1).join("][") + "]";
    }
    console.log("Original: " + key + ", updated: " + updated);
  });
});
&#13;
&#13;
&#13;

如果你还在努力显示表单控件旁边的数组中的所有错误,那么你只需循环遍历它们。您正在接收一个对象,其中对象中的属性名称是表单控件名称,值是错误消息的数组。所以我们

  1. 遍历该对象的属性名称,以及每个属性名称:
  2. 标记相关控件,
  3. 遍历该条目的错误数组,将其追加到alertHtml
  4. 这些行很长:

    &#13;
    &#13;
    var errors = {
      "education.1.yearbegin":["The education.1.yearbegin field is required."],
      "education.2.yearbegin":["The education.2.yearbegin field is required."]
    };
    function fixKey(key) {
      var updated = key.split(".");
      if (updated.length == 1) {
        updated = updated[0];
      } else {
        updated = updated[0] + "[" + updated.slice(1).join("][") + "]";
      }
      return updated;
    }
    var alertHtml = '<ul>';
    // #1: Loop through the object's property names
    Object.keys(errors).forEach(function(key) {
      // #2: Mark the control, using the corrected name
      $('.form-control[name="' + fixKey(key) + '"]').closest('.form-group').addClass('has-error');
      // #3: Loop through the errors
      errors[key].forEach(function(msg) {
        alertHtml += '<li>' + msg + '</li>';
      });
    });
    alertHtml += "</ul>";
    $(document.body).append(alertHtml);
    &#13;
    .has-error {
      border: 1px solid red;
    }
    &#13;
    <div class="form-group">
      <input name="education[1][yearbegin]" type="date" class="form-control">
    </div>
    <div class="form-group">
      <input name="education[2][yearbegin]" type="date" class="form-control">
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    &#13;
    &#13;
    &#13;

答案 1 :(得分:0)

名称的第一个问题:

我只是将名称更改为更易于阅读的内容,而不是将其更改为:

name="education[1][yearbegin]"

也许有这样的想法:

name="EducationYearBegin1"

关于第二个问题:

您可以检查该属性是否为数组,如下所示:

if (value instanceof Array) {
    value.forEach(function (item) {
        alertHtml += '<li>' + item + '</li>';
    })
} else {
    alertHtml += '<li>' + value + '</li>';

}

也许是这样的?

如果您的阵列中也有多个错误,foreach会覆盖您。

答案 2 :(得分:0)

您可以使用String#replaceeducation.1.yearbegin转换为education[1][yearbegin]

请参阅此代码中的fixName函数。

&#13;
&#13;
function fixName(name) {
  var newName =  name.replace(/\.\d\./, function ($1) {
    return "[" + $1.replace(/\./g, "") + "]"
  }).replace(/\].+/, function ($1) {
    return $1.replace(/\]/, "][") + "]"
  });

  return newName;
}

var errors = [{"education.1.yearbegin":["The education.1.yearbegin field is required."]},
{"education.2.yearbegin":["The education.2.yearbegin field is required."]}]; //$.parseJSON(data.responseText);
var alertHtml = document.querySelector("#alert");

alertHtml.innerHTML += '<ul>';
$.each(errors, function (key, obj) {
var realKey = fixName(Object.keys(obj)[0]);
    $('.form-control[name="'+ realKey +'"]').addClass('has-error');
    
    alertHtml.innerHTML += '<li>' + obj[Object.keys(obj)[0]][0]  + '</li>';
});
alertHtml.innerHTML += "</ul>";
&#13;
.has-error {
  color: red;
}

li {
  color: green
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="education[1][yearbegin]" type="date" class="form-control">
<input name="education[2][yearbegin]" type="date" class="form-control">

<div id="alert"></div>
&#13;
&#13;
&#13;