Showing valid message
← ejemplos
The plugin only provides error message option which is shown when the field is invalid. Is it possible to add a valid message option shown if the field is valid?
The quick answer is YES. This example shows you how to implement this feature.
Assuming that our form has two text boxes which are username and password.
As usual, the plugin is called by following snippet code:
The implementation idea consists of four steps as following.
Adding valid message option
I add an option named validMessage
for each field. As the name suggests, the
plugin will show the valid message when the field is valid.
We can get the option value later via the getOptions()
method.
Creating an element that shows the invalid message
Basically, you can place the valid message anywhere you want as long as you can retrieve it later.
Behind the scenes, FormValidation places each error message in a span
element. The field error messages are placed inside an element which can be retrieved by
$field.data('bv.messages')
.
To make the example easily to follow, I simply create a span
element right
after each field for showing the valid message:
In fact, the number of fields might be greater than two as in our example. Therefore, it
is much better if these valid message elements are created dynamically. It's quite easy
to do it by triggering the init.field.fv
event:
In step 2 above, the custom option validMessage
is determined by using the
getOptions()
method.
Showing the valid message when the field is valid
Triggering the success.field.fv
event to
do that:
Hiding the valid message when the field is invalid
Finally, being similar to the step 3, the valid message must be hidden when the field
turns to be invalid. It can be done via the err.field.fv
event:
Final result
Below is the final working example: