[英]Semantic UI: How to prevent form from being submitted when validation fails?
我有一个基本的登录表单,我已经在我的javascript文件中指定了表单验证和API调用。 我遇到的问题是,当我单击登录按钮并且表单有错误时,无效字段将突出显示但仍然进行API调用,即使表单无效。
这是一个简化的例子:
<form class="ui form">
<div class="field">
<input name="username" type="text" placeholder="Username" autofocus>
</div>
<div class="field">
<input name="password" type="password" placeholder="Password">
</div>
<button type="submit" class="ui submit button">Login</button>
<div class="ui error message"></div>
</form>
$(function() {
$('form').form({
username: {
identifier: 'username',
rules: [{
type: 'empty',
prompt: 'Please enter your username'
}]
},
password: {
identifier: 'password',
rules: [{
type: 'empty',
prompt: 'Please enter your password'
}]
}
}, {
onFailure: function() {
// prevent form submission (doesn't work)
return false;
}
});
// *** this API call should not be made when the form is invalid ***
$('form .submit.button').api({
action: 'login',
method: 'post',
serializeForm: true,
dataType: 'text',
onSuccess: function() {
// todo
},
onError: function() {
// todo
}
});
});
我错过了什么? .api()
和.form()
调用是否正确?
好吧我明白了。 我需要做的就是改变
$('form .submit.button').api(...
至
$('form').api(...
我没有意识到我可以直接在<form>
元素上调用.api()
。 现在当表单无效时没有进行api调用,因为表单没有提交(之前我在提交按钮上有api调用,当表单无效时没有取消)。
使用onSuccess事件而不是api方法。
$('form').form({
username: {
identifier: 'username',
rules: [{
type: 'empty',
prompt: 'Please enter your username'
}]
},
password: {
identifier: 'password',
rules: [{
type: 'empty',
prompt: 'Please enter your password'
}]
}
}, {
onFailure: function() {
// prevent form submission (doesn't work)
return false;
},
onSuccess:function(event,fields){
// prevent form submission
// api / ajax call
return false;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.