Frontend UI form validation with Bootstrap or MDBootstrap. This library allows you to easily create form validation in your application.
- Usage
- Validation on Submit
- Validation on Blur
- Manual Validation
- Types of Validation
- Multiple Validations at Once
- Scroll on Validation Fail
- Simple Example
- Make sure JQuery is loaded in the DOM before this script.
- Load the script on the dom
<script src="bootstrap-form-validation.js"></script>
<form data-validate-on-submit="true">...</form>
<form data-validate-on-blur="true">...</form>
<script>
const validationResult = BootstrapValidation.process("#login-form");
// Returns { errors: [], valid: true }
if (validationResult.valid === false) {
// Do some validation here
}
</script>
Below are the types of validation this library can use so far.
Trims the whitespace, if any, at the beginning or end of the value.
data-validate-validation="trim"
Marks the input as required and will not accept a null or empty response.
data-validate-validation="required"
Marks the input as required valid address.
data-validate-validation="email"
Requires the input to be a minimum amount of characters.
data-validate-validation="min_length[5]"
Requires the input to be equal to or less than a number of characters.
data-validate-validation="max_length[12]"
Requires the value to be a number.
data-validate-validation="number"
Requires the value of the input to match another input's value. (Example: password and confirm password)
data-validate-validation="required|matches[#inputId]"
You may run multiple validations on an input like so:
data-validate-validation="trim|required|email"
Sometimes we may want the page to scroll to the top of the form when validation fails. To do this, simply add the following to the form element as an attribute:
data-validate-scroll-on-fail="true"
<form data-validate-on-submit="true" method="POST" action="">
<div class="form-floating">
<input data-validate-validation="required|email" name="email" type="text" class="form-control"
id="floatingInput" placeholder="name@example.com">
<label for="floatingInput">Email address</label>
</div>
<div class="form-floating">
<input data-validate-validation="required|min:5|max:12" type="password" class="form-control"
id="floatingPassword" placeholder="Password">
<label for="floatingPassword">Password</label>
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button>
</form>