我能够以不同的方式实现这一点,因为 button type=button 控件在忽略验证的同时没有提交,如果我手动提交,semanticui 的默认事件处理程序将进行干预并显示验证错误。
我的用例有两个按钮,一个是保存草稿,另一个是finalize(最终保存)。第一个必须按原样保存数据,而不触发验证,而另一个将触发验证然后保存。
我还使用我为该项目自定义实现的数据属性来实现所有验证器,因此表单验证器位于 JS 文件中。
在我的表单验证失败方法中,我包含了一个委托函数,我可以在我的页面上设置它并根据单击它的按钮,然后能够返回 true 或 false。
我在 JS 文件中的表单验证器
$('.ui.form').form({
inline: true,
on: 'submit',
fields: formFields,
transition: 'fade',
keyboardShortcuts: false,
onFailure: function () {
var returnValue = false; //Default to false, since validations failed
//If the delegate is present, fire it to evaluate
if (typeof window.delegValidate == 'function') {
returnValue = window.delegValidate();
}
//Ignore the toast if the delegate evaluated to TRUE
if (!returnValue) {
$('body')
.toast({
title: 'Unable to save',
message: 'Please enter all required field data before saving.',
classProgress: 'red',
showProgress: 'top',
progressUp: true,
position: 'bottom right',
showIcon: 'red exclamation triangle'
});
}
return returnValue; // false is required if you don't want to let it submit
}
});
在我的页面上,我在窗口中附加了一个函数,因为我的表单验证位于 JS 文件中。
页面功能
//For all postback buttons, save the id value in a hidden field for use in the delegate
$('.postbackButton').bind('click', function (e) {
$('#ButtonClicked').val(this.id); // a hidden field on the page
});
//setting the delegate for use in the form validations
window.delegValidate = function () {
//For the save button, just ignore the validations and return true
//This in turn is invoked by the failure method of the form validation that is
//dynamically attached to the page, and hence this return value is respected
//over the false that is otherwise sent back for when we want to interrupt the page
//since there are errors normally.
if ($('#ButtonClicked').val() == 'Save')
return true;
else // if value is finalize, let it return false
return false;
}
对于我不想要此功能的其他页面,我可以简单地不编写委托方法,并且在提交按钮上按预期触发默认验证。
希望这可以帮助仍在寻找方法的人。 :)