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:
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).
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: