-
Notifications
You must be signed in to change notification settings - Fork 379
phone validation with multiple masks via jQuery Inputmask wrapped in ko.validation extender
Inside your ko.validation.rules[] extender you can use external library to do actual validation. Here is how you can integrate jQuery Inputmask source at Github. Reason is, this library can offer some advanced features, like validating a phone with [auto-selection of] multiple masks.
Note: it's just an example, may be inefficient, just shows some opportunities. See full example at Jsfiddle, and read its comments. It's showing the country your phone is from, + a country flag with a bit of tweaking.
Basic steps are as follows:
- we include libraries, tested on:
jQuery, knockout 3.4.0, knockout-validation 2.0.3 jquery.inputmask 3.2.7 (earlier versions are not advised, see comments in the fiddle phone-codes.js for jquery.inputmask flag-icon-css (https://github.com/lipis/flag-icon-css)
-
we apply Inputmask to our input:
$(document).ready(function(){ //Inputmask('phone').mask('#forinputmask'); /* a variant of setting a mask */ $('#forinputmask').inputmask("phone"); });
-
we add Knockout's part:
ko.validation.rules['phone-inputmask'] = { validator: function (val) { /* -=IMPORTANT=-: if server sends later back the unmasked value, then uninstead of 'val', consider comparing to 'Inputmask.format(val, { alias: 'phone'});' */ return Inputmask.isValid(val, { alias: 'phone'}) }, message: 'Incorrect or incomplete phone' }; /* Needed ONLY if ko.validation.init() was prior to inclusion of custom rule */ //ko.validation.registerExtenders(); ko.validation.init({ registerExtenders: true, /* obsolete for new versions of ko.validation like 2.0.3, it's now auto-done in lib source, AFAIK */ messagesOnModified: true, insertMessages: true, }, true); var myVM = { phone: ko.observable().extend({'phone-inputmask': {params: 'phone'}, rateLimit: { timeout: 200, method: "notifyWhenChangesStop" } }) }; ko.applyBindings(myVM);
Pls also note rateLimit: { timeout: 200...
part, that seems to help reduce CPU load.