Getting notified while field is being validated
← ejemplos
When using either callback, promise or remote validator, your validation logic might take time. For instance, the remote validator connects to the server side and executes a few of database queries to check whether or not the field is valid. These kind of process could force the user to wait for a busy processing. User even don't have idea about what is happening.
This example introduces two ways to get user notified while the validation is being processed. It enhances the user experience of the application.
Setting validating icon
The first and most simple way is using a loading icon. It can be set via the icon option:
$(form).formValidation({
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
}
});
The icon.validating
icon then is shown up when the field is being validated.
In the following table, you can find the icon provided by supported frameworks:
Icon sets | Icon classes |
---|---|
Glyphicons |
|
FontAwesome |
|
Semantic icons |
|
UIKit |
|
Here is the result:
Listening event
When the plugin starts validating field, it triggers the status.field.fv event:
$(form)
.formValidation({
...
})
.on('status.field.fv', function(e, data) {
// data.field is the field name
// data.element is the field element
// data.fv is the plugin instance
// data.status is the field status which is 'VALIDATING' when the validation starts
// data.validator is the name of current validator
});
By listening this event, we can do whatever we want to inform user about the validation process. To make it simple, I am going to use the Bootstrap progress bar component which is shown right after the validation begins its job. It is also hidden when the validation process completes.
The form markup:
<div class="form-group">
<label class="col-lg-3 control-label">Username</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="username" autocomplete="off" />
<!-- The progress bar is hidden initially -->
<div class="progress" id="progressBar" style="margin: 5px 0 0 0; display: none;">
<div class="progress-bar progress-bar-success progress-bar-striped active" style="width: 100%"></div>
</div>
</div>
</div>
The Javascript code:
$(form)
.formValidation({
fields: {
username: {
validators: {
remote: {
type: 'POST',
url: '/path/to/your/api/',
message: 'The username is not available'
}
}
}
}
})
.on('status.field.fv', function(e, data) {
// Change “username” to your field name
if (data.field === 'username' && data.validator === 'remote') {
(data.status === 'VALIDATING')
? $('#progressBar').show() // Show the progress bar while we are validating
: $('#progressBar').hide(); // Otherwise, hide it
}
});
The screenshot below demonstrates how it looks: