我试图自动使用jQuery显示Laravel 5.5 Ajax错误验证,
当单个字段工作时,使用以下代码:
$.each(response.errors, function (key, value) {
el.find('input[name="'+key+'"] , select[name="'+key+'"] , textarea[name="'+key+'"]').parent().append('<div class="error right-align pink-text text-mute">'+value+'</div>');
});
上面的代码会根据选择器向每个元素附加一条错误消息。
但是如果我使用数组字段,例如<input type="text" name="start_date[]" />
然后我得到了以下错误验证:
{"message":"The given data was invalid.","errors":{"start_date.0":["The start_date.0 field is required when availability is 0."],"start_date.1":["The start_date.1 field is required."],"end_date.0":["The end_date.0 field is required."],"end_date.1":["The end_date.1 field is required."]}}
所以我的javascript无法找到元素 start_date.0
如何使用带有该响应的jQuery选择元素? (start_date.0,start_date.1)
答案 0 :(得分:0)
使用errors['start_date.0']
代替errors.start_date.0
var myObj = {"message":"The given data was invalid.","errors":{"start_date.0":["The start_date.0 field is required when availability is 0."],"start_date.1":["The start_date.1 field is required."],"end_date.0":["The end_date.0 field is required."],"end_date.1":["The end_date.1 field is required."]}};
console.log(myObj.errors['start_date.0']);
使用start_date.0
它会尝试在对象0
中获取元素start_date
,但您将此start_date.0
作为errors
的元素,因此请使用方括号{{1将[ ]
视为start_date.0
errors
var response = {"message":"The given data was invalid.","errors":{"start_date.0":["The start_date.0 field is required when availability is 0."],"start_date.1":["The start_date.1 field is required."],"end_date.0":["The end_date.0 field is required."],"end_date.1":["The end_date.1 field is required."],"dob":["Date of birth is required."]}};
$.each(response.errors, function (key, value) {
var name = $("input[name='"+key+"']");
if(key.indexOf(".") != -1){
var arr = key.split(".");
name = $("input[name='"+arr[0]+"[]']:eq("+arr[1]+")");
}
name.parent().append('<div class="error right-align pink-text text-mute">'+value[0]+'</div>');
});
答案 1 :(得分:0)
感谢所有答案,我通过使用id属性来解决这个问题,所以我的html标签应该像这样<input type="text" id="start_date.0" name="start_date[]" />
因为jquery不允许点“。”选择器中的模式,我的选择器应该是这样的
el.find('input[id="select_date.0"]')
所以我的代码应该是:
$.each(response.errors, function (key, value) {
el.find('input[id="'+key+'"],input[name="'+key+'"] , select[name="'+key+'"] , textarea[name="'+key+'"]').parent().append('<div class="error right-align pink-text text-mute">'+value+'</div>');
});
答案 2 :(得分:-1)
error: function(data){
var response = JSON.parse(data.responseText);
var errorString = '<ul style="list-style: none;">';
$.each( response.errors, function( key, value) {
errorString += '<li><small>' + value + '</small></li>';
});
errorString += '</ul>';
$("#errors").html(errorString);
}