语义UI:如何防止验证失败时提交表单?
作者:互联网
我有一个基本的登录表单,并且在我的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
},
one rror: function() {
// todo
}
});
});
我也有一个punkr here,它演示了我遇到的问题.
我错过了什么? .api()和.form()调用正确吗?
解决方法:
好吧,我知道了.我要做的就是改变
$('form .submit.button').api(...
至
$('form').api(...
我没有意识到我可以直接在< form>上调用.api().元件.现在,由于表单未提交而导致表单无效时,不会进行api调用(以前,我在“提交”按钮上进行了api调用,当表单无效时,不会取消api调用).
标签:html5,semantic-ui,javascript,jquery 来源: https://codeday.me/bug/20191028/1955769.html