语义 UI:如何防止在验证失败时提交表单

Semantic UI: How to prevent form from being submitted when validation fails?

本文关键字:失败 提交 表单 验证 UI 何防止 语义      更新时间:2023-09-26

我有一个基本的登录表单,我已经在我的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;
        }
    });