下面我尝试使用HTML 5验证和custom styles from the Bootstrap 4 form page在每个字段下方显示错误消息。
Bootstrap中的默认自定义样式技术似乎不允许任何机制更新错误消息,特别是HTML 5现在为电子邮件输入字段提供的错误消息。我已经推出了自己的Javascript来执行此操作。
有没有更合适的Bootstrappy方法呢?
$( "#needs-validation" ).submit(function( event ) {
if (this.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
this.classList.add('was-validated');
});
// Email validation.
$( "#email" ).change(function() {
var email = $(this);
if (email.is(':invalid')) {
email.removeClass('is-valid').addClass('is-invalid');
email.siblings(".invalid-feedback").text(email.prop("validationMessage"))
} else {
email.removeClass('is-invalid').addClass('is-valid');
}
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
<form class="container" id="needs-validation" novalidate>
<div class="row">
<div class="col-md-6 mb-3">
<label for="validationCustom03">Email address</label>
<input type="email" class="form-control" id="email" placeholder="email address" required>
<div class="invalid-feedback">
Please provide a valid email.
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom04">Name</label>
<input type="text" class="form-control" id="validationCustom04" placeholder="Name" required>
<div class="invalid-feedback">
Please provide a valid name.
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
&#13;