Validating form manually

In most cases, the form can be validated automatically when user click its Submit button via the SubmitButton plugin. FormValidation also allows us to validate the form manually by using the validate() method.
The following piece of code demonstrates how to validate a form when user click on a normal button:
<form>
<!-- It is a normal button -->
<button id="loginButton" type="button">Login</a>
</form>
<script>
document.addEventListener('DOMContentLoaded', function(e) {
// Create a FormValidation instance
const fv = FormValidation.formValidation(demoForm, {
fields: { ... },
plugins: { ... },
});
const loginButton = document.getElementById('loginButton');
loginButton.addEventListener('click', function() {
fv.validate().then(function(status) {
// status can be one of the following value
// 'NotValidated': The form is not yet validated
// 'Valid': The form is valid
// 'Invalid': The form is invalid
...
});
});
});
</script>
We are able to improve the user experience by letting user know that the form is going to be validated. It's useful if the validation takes time (let's say that you are using the remote validator).
For example, by triggering the core.form.validating event, we can show a progress bar or simply update the button content such as:
const loginButton = document.getElementById('loginButton');
// Create a FormValidation instance
const fv = FormValidation.formValidation(demoForm, {
fields: { ... },
plugins: { ... },
}).on('core.form.validating', function() {
loginButton.innerHTML = 'Validating ...';
});
loginButton.addEventListener('click', function() {
fv.validate().then(function(status) {
// Update the login button content based on the validation status
loginButton.innerHTML = (status === 'Valid')
? 'Form is validated. Logging in ...'
: 'Please try again';
});
});
Validating form manually

See also