When I talked about Validatious previously, I had written almost no Javascript and had no need for any validations besides making sure that fields were required and of a certain minimum length.
On another project, I needed to validate some North American phone numbers and Canadian postal codes. It turned out to be really simple to add custom validations. Here’s how it’s done.
First, here’s a form:
Note that I’ve added a class of cdnpostalcode to the postal code input and a class of phone to the phone number input. You still need the required class to turn on the validation.
This won’t do anything other than require that the inputs be filled out yet, as we haven’t added our custom validators in. To register a validator, you do something like this:
Most of the time, the callback is a regular expression. Let’s tackle the Canadian Postal Code one first, as they’re a bit simpler.
A Canadian Postal Code looks like A1A 1A1 or S7J 3A2 or H0H 0H0 ( bet you didn’t know that Santa lived in Canada! ). It’s letter-number-letter space number-letter-number. The space is optional, too. So, a regular expression to match a Canadian Postal Code might look like this:
/^\w\d\w\s*\d\w\s$/
We’ll register the class cdnpostalcode to trigger this validation like this:
The phone number validator is exactly the same, except the regular expression is a bit more hairy. This regex is from regexlib.com (I added in the part that accepts an extension).
If we add those two chunks of Javascript to the HTML that calls our form, then they will validate the postal code and phone number correctly. The only problem is that the validation error message will be something like “Postal Code does not pass cdnpostalcode validator”. Not very pretty. There are a few more options to Validator.reg that will allow us to fix that.
The signature for Validator.reg looks like this (it’s in src/core/validator.js):
So far, we’ve only used the first two parameters (name and fn). The params argument would allow us to specify the parameters used in the validator. We don’t need that, so we’ll pass in null. Then, we can set the default message. Like this: