What if you want to attach more data to the returned value and reuse it later? Fortunately, in addition to the boolean value indicating the field validity, it's easy to include more data to the returned value of validators as following:
Then you can get the returned value when triggering the validator events:
In the next section, I will demonstrate how to use this approach in some examples.
Password strength meter
The following example shows how strong a password is. We define various rules to define a strong password. Each rule provides a score for the password if it passes the rule.
When user change the password, we loop over the rules and calculate the score. Finally, based on the score, we display the password strength which can be one of the following levels:
Very weak, if the score is less than 0
Weak, if the score is between 0 and 2
Medium, if the score is between 2 and 4
Strong, if the score is greater than 4
To archive this, we use the callback validator to calculate the password score. And then trigger the success.validator.fv event to get the score, and show up the level. Looking at the code will give you the implementation details.
The rules and their scores in this example are simple as for demonstrating purpose only. In fact, it's up to you to define more rules and strength levels
In a form for signing up new account, we often use the remote validator to check if the username is available or not.
We can query against the database to check the availability of username which is similar to the given one. And then suggest them to user if they are not taken.
For instance, the remote URL might suggests a list of available username with the full responses as below:
The following form shows how this approach works in action:
For testing purpose, the back-end used in the example always responses the same list of available username