Reputation: 127
I'm having a problem with understanding the building validation forms. In bootstrap current documentation there is a piece of JS code (so called starter code):
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('needs-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
</script>
and it works fine but what should I do if i want to implement password check, for example? If i inderstand it right Bootstrap has css classes :valid and :invalid which run when the field is empty. I want to fire them when some condition is the (ie password less than 8 symbols).
<form id="needs-validation" novalidate>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputPassword1">Password</label>
<input type="password" class="form-control" name="inputPassword1" id="pass1" placeholder="password" required>
<div class="invalid-feedback">
Please provide a valid password.
</div>
</div>
</form>
Upvotes: 2
Views: 6569
Reputation: 12711
You could use the pattern attribute. From MDN:
pattern A regular expression that the control's value is checked against. The pattern must match the entire value, not just some subset. Use the title attribute to describe the pattern to help the user. This attribute applies when the value of the type attribute is text, search, tel, url, email, or password, otherwise it is ignored. The regular expression language is the same as JavaScript RegExp algorithm, with the 'u' parameter that makes it treat the pattern as a sequence of unicode code points. The pattern is not surrounded by forward slashes.
For example, the following will validate that the password is at least 8 characters with upper case, lower case and numbers:
<form id="needs-validation" novalidate>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputPassword1">Password</label>
<input type="password" class="form-control" name="inputPassword1" id="pass1" placeholder="password"
pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$"
required>
<div class="invalid-feedback">
Passwords should be a minimum of 8 characters and include at least one upper case letter, one lower case letter and one number.
</div>
</div>
</form>
Upvotes: 3