在Rainlab Relax Theme 的“联系表”页面上有一个很好的例子。它使用了一小部分 JQuery 代码,可以根据您的用例进行调整和修改。由于 Rainlab Relax 示例主题发布在 MIT license 下,我认为这是为了将使用过的小 JQuery 处理程序的 JS 代码完整粘贴到此处,并留给您了解内部工作原理以及如何调整其方法满足您的需求:
来自 Rainlab 放松主题中的文件 assets/javascript/app.js:
/*
* Implement nice invalid form fields
*/
$(window).on('ajaxInvalidField', function(event, fieldElement, fieldName, errorMsg, isFirst) {
var $field = $(fieldElement).closest('.form-group'),
$help = $('<p />').addClass('help-block')
if (!$field.length) {
return
}
event.preventDefault()
if (errorMsg) {
$help.text(errorMsg.join(', '))
}
$help.addClass('form-field-error-label')
$field.addClass('has-error')
// Prevent the next error alert only once
$(window).one('ajaxErrorMessage', function(event, message){
event.preventDefault()
})
if ($('.form-field-error-label', $field).length > 0)
return
$field.append($help)
// Scroll to the form group
if (isFirst) {
$('html, body').animate({ scrollTop: $field.offset().top }, 500, function(){
fieldElement.focus()
})
}
})
简而言之,当服务器端的表单处理程序抛出 ValidationException 时,这会捕获由十月框架触发的 ajaxInvalidField 事件,即在此示例中(仍然来自 Rainlab Relax 主题代码):
function onSubmit()
{
$rules = [
'name' => 'required|min:2|max:64',
'phone' => 'required',
'email' => 'required|email|min:2|max:64',
'comments' => 'required|min:5',
];
$validation = Validator::make(post(), $rules);
if ($validation->fails()) {
throw new ValidationException($validation);
}
}
上面的 JQuery 代码基本上只是简单地阻止默认事件响应(以在 alert() 中显示错误消息),而是在末尾附加一个包含适当验证错误消息的 <p class="help-block form-field-error-label" /> <div class="form-group" />在此示例中您需要围绕您的输入,并将 has-error 类添加到该<div class="form-group" />,以及一些可能不需要在此处详细介绍的其他详细信息。
我想你大概可以从那里弄清楚你需要什么。 HTH。 :)