【问题标题】:Combine client-side and server-side validation in Bootstrap 4 form在 Bootstrap 4 表单中结合客户端和服务器端验证
【发布时间】:2018-07-06 07:40:32
【问题描述】:

我有一个带有输入字段的 Bootstrap 4 表单,名为 runname。我想对输入字段进行以下验证:

  • runname不能为空
  • runname 不能包含空格
  • runname以前不能用过

如果输入字段为空,则使用custom Bootstrap styles 给出错误的表单代码:

// JavaScript for disabling form submissions if there are invalid fields
(function() {
  'use strict';
  window.addEventListener('load', function() {
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.getElementsByClassName('needs-validation');
    // Loop over them and prevent submission
    var validation = Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('submit', function(event) {
        if (form.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        }
        form.classList.add('was-validated');
      }, false);
    });
  }, false);
})();
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>

<body class="bg-light">
  <div class="container">
    <div class="col-md-12 order-md1">
      <form class="needs-validation" novalidate method="post" action="#">
        <div class="form-group row">
          <label for="inputRunname" class="col-sm-2 col-form-label">Run name</label>
          <div class="col-sm-10">
            <input type="text" class="form-control" id="inputRunname" name="runname" placeholder="Run name" required>
            <div class="invalid-feedback">
              Please enter a run name
            </div>
          </div>
        </div>
        <div class="form-group row">
          <div class="col-sm-10">
            <button type="submit" class="btn btn-primary">Submit</button>
          </div>
        </div>
      </form>
    </div>
  </div>
  <!-- Optional JavaScript -->
  <!-- jQuery first, then Popper.js, then Bootstrap JS -->
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>

</body>

</html>

我有一些 Javascript 来检查输入是否包含空格:

function cannotContainWhiteSpace(input, errorId, name) {
  var value = input.value;
  var errMsgHolder = document.getElementById(errorId);
  if (!(/^\S*$/.test(value))) {
    errMsgHolder.innerHTML =
      'The ' + name + ' cannot contain whitespace';
    input.focus();
    return false;
  }
}

我的 Cherrypy 后端也有一些 Python 代码,它会在数据库中查找 runname 是否已经存在:

try:
    myConnection = mysql.connector.connect(host=self.database['host'], user=self.database['user'], passwd=self.database['passwd'], db=self.database['db'])
    cursor = myConnection.cursor(buffered=True)

    # unless overriden by the force flag, check whether the runname has already been used before
    if not force:
        reusedrunquery = "SELECT run FROM logs WHERE run = %s AND errormessage IS NULL"
        cursor.execute(reusedrunquery, (runname,))
        if cursor.fetchall():
            flag = True
            cherrypy.session['reusedRun'] = True
    myConnection.close()
except mysql.connector.Error as err:
    return self.database_failure(str(err))

但我不知道如何将所有这些不同的部分拼凑在一起以获得一个同时具有两个客户端验证和服务器端验证的表单。

【问题讨论】:

  • 我认为你可以在表单提交上结合所有表单验证。但是服务器端逻辑相关检查应该单独处理

标签: validation bootstrap-4 cherrypy


【解决方案1】:

在提交事件时,您的后端应该有一个实际拦截请求的方法,我认为您应该能够与后端的逻辑建立连接。

步骤如下:

  1. 表单编译正确
  2. Http POST 请求启动onSubmit 事件
  3. 后端接收请求并通过收集负责接收 Http POST 请求的方法上的数据来应用进一步的逻辑

否则,您可以尝试进行 AJAX 调用,在该调用上将执行客户端验证,然后它将调用服务器端方法/类以检查 runname 是否具有已经用过了。

【讨论】:

    【解决方案2】:

    大多数时候我使用自定义样式来实现这一点。

    .invalid-feedback{
      display:none;
    }
    
    .invalid .invalid-feedback {
      display:block;
    }
    
    <form novalidate>
      <div class="form-group">
        <label>Label</label>
        <input class="form-control" name="runname" type="text">
        <div class="invalid-feedback"></div>
      </div>
    </form>
    

    在 Javascript 中

    验证输入控件并设置 css 类和消息文本。在您的情况下,验证不是空的,没有空格,并且尚未使用[服务器端]。 如果无效,将invalid 类添加到父form-group,并在输入控件旁边的invalid-feedback div 中设置验证消息。

    【讨论】:

    • 在显示服务器端错误消息后它不会更新消息。例如:我显示“电子邮件已被占用”。在无效反馈元素中。然后,我清除电子邮件字段并尝试提交。它没有为空字段显示正确的消息。有办法处理吗?
    猜你喜欢
    • 2011-10-17
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多