如何从自定义外部脚本中触发默认的Bootstrap 4表单验证错误消息

时间:2019-04-16 13:20:49

标签: javascript jquery twitter-bootstrap forms validation

在我们的联系表格中,由于我们只能在一个国家/地区开展业务,因此我只允许来自美国的电子邮件地址进行提交。尝试提交表单时,如何触发默认错误消息,以使“无效”消息的显示方式与“名字”和“姓氏”字段的显示方式相同?

在下面的代码中,出于示例的原因,我仅允许使用“ com”,“ edu”,“ gov”,“ net”,“ org”。目的是每当在电子邮件字段中输入除上述地址以外的其他电子邮件地址时,就会触发一条消息。

$(document).ready(function() {
  $(function() {
    $("#testform").submit(function() {
      str = $('input[name=emailAddress]').val();
      str = str.split('@').slice(0);
      str = str[1].split('.').slice(0);

      var allowedDomains = ['com', 'edu', 'gov', 'net', 'org'];

      alert("str = " + str[1]);

      if ($.inArray(str[1], allowedDomains) !== -1) {
        alert(str + ' is allowed');

      } else {
        alert('not allowed');
        event.preventDefault();
        event.stopPropagation();
        $('#emailAddress').addClass('invalid');
      }
    });
  });
});
<link href="https://getbootstrap.com/docs/4.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://getbootstrap.com/docs/4.0/assets/js/vendor/holder.min.js"></script>
<script src="https://getbootstrap.com/docs/4.0/dist/js/bootstrap.min.js"></script>
<script src="https://getbootstrap.com/docs/4.0/assets/js/vendor/popper.min.js"></script>

<div class="container">
  <form action="" method="post" target="" class="needs-validation" role="form" id="testform">
    <fieldset>
      <div class="form-group">
        <label for="firstName" class="col-form-label">Customer first name:
    <input type="text" class="form-control" name="firstName" id="firstName" required aria-required="true">
    </label>
      </div>
      <div class="form-group">
        <label for="lastName" class="col-form-label">Customer last name:
    <input type="text" class="form-control" name="lastName" id="lastName" required aria-required="true">
    </label>
      </div>
      <div class="form-group">
        <label for="emailAddress" class="col-form-label">Customer email address:
    <input type="email" class="form-control" name="emailAddress" id="emailAddress" required placeholder="Enter valid email" aria-required="true">
    </label>
      </div>
      <div class="form-group">
        <button type="submit" class="btn btn-primary">Submit</button>
      </div>
    </fieldset>
  </form>
</div>

0 个答案:

没有答案