[英]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.