Laravel验证使用点数组语法的JQuery查找输入名称

时间:2019-07-08 10:06:26

标签: javascript jquery laravel

如果我具有Laravel的点数组语法,如何按名称在JQuery输入中查找?

输入示例:

<input type="text" name="Payments[0][1][Amount]">
<input type="text" name="Reservations[0][Date]">

来自ajax请求的Laravel验证响应:

errors: {
  Payments.0.1.Amount: "Field is required",
  Reservations.0.Date: "Field should be date"
}

问题:如果我只有数组点名称,如何在javascript访问输入名称中遍历error数组?

例如,将Payments.0.1.Amount转换为Payments[0][1][Amount],或将Reservations.0.Date转换为Reservations[0][Date]

for (const [key, value] of Object.entries(errors)) {
     key = somehowParseDotInputToArray(key); // how? :)
   $('#app input[name="' + key + '"]').append( '<p class="error">'+ value +'</p>' );
}

3 个答案:

答案 0 :(得分:1)

已经找到了解决方案,也许有人也可以提供帮助:)

function DotArrayToJs(str){
  var splittedStr = str.split('.');

  return splittedStr.length == 1 ? str : (splittedStr[0] + '[' + splittedStr.splice(1).join('][') + ']');
}

答案 1 :(得分:1)

只需从.的错误对象中拆分名称。使用var $nameArr = name.split('.');

假设name = Reservations.0.Datelet nameArr = ['Reservations','0','Date']

然后根据需要命名

var newName = $nameArr[0] + '['+ $nameArr[1] +']' + '[' +$nameArr[2] + ']';

newName看起来像Reservations[0][Date]

为所有名称变量循环此过程并创建新的错误对象。

答案 2 :(得分:0)

Juste,以防有人拥有多级数组

	function getFieldnameFromLaravelDotName(laravelDotName) {

		let parts = laravelDotName.split(".");
		let fieldName = "";
		let prefix = "";
		let suffix = "";
		parts.forEach((part, i) => {

			if (fieldName != "") {

				prefix = "[";
				suffix = "]";

			}

			fieldName += prefix + part + suffix;

		});

		return fieldName;

	}
  
  console.log(getFieldnameFromLaravelDotName("noDotInThis"));
  console.log(getFieldnameFromLaravelDotName("one.level"));
  console.log(getFieldnameFromLaravelDotName("many.level.array.plop"));