-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Howto: Create your own mask
A day will come where you cannot create your mask with the default definitions or with any predefined aliases. So it's time to create it yourself.
Issue 220 - The following struggle. I would like to allow decimals in a phone field. The format/mask is free to enter for the user, but i would only allow one '-' for instance: 06-12345678
How can i restrict the dashes to one?
First thing to check: What is already available? Does an alias exist? Does a definition exist? What gets us closest?
a mask like $(selector).inputmask("9", { repeat: 10, greedy: false}); is close.
So we start with the definition of 9 and rename it to p (p ~ phonenumber)
'9': {
validator: "[0-9]",
cardinality: 1
}
'p': {
validator: "[0-9]",
cardinality: 1
}
We need to allow the definition to allow a '-' in the mask. So we adjust the regex to just do that.
'p': {
validator: "[0-9\\\-]",
cardinality: 1
}
Now using a mask like $(selector).inputmask("p", { repeat: 10, greedy: false}); allows for input of numbers including a minus.
But we only want 1 minus allowed.
Let's rewrite the same definition as a function instead of a regex.
'p': {
validator: function (chrs, buffer, pos, strict, opts) {
return new RegExp("[0-9\\-]").test(chrs);
},
cardinality: 1
}
In order to see if there is only one instance of the - we need to validate on the whole input.
'p': {
validator: function (chrs, buffer, pos, strict, opts) {
var cbuffer = buffer.slice();
cbuffer.splice(pos, 0, chrs);
var bufferStr = cbuffer.join('');
return new RegExp("^[0-9\\-]*$").test(bufferStr);
},
cardinality: 1
}
And finally make some changes to the regex to restrict the -
'p': {
validator: function (chrs, buffer, pos, strict, opts) {
var cbuffer = buffer.slice();
cbuffer.splice(pos, 0, chrs);
var bufferStr = cbuffer.join('');
return new RegExp("^[0-9]*(\\-)?[0-9]*$").test(bufferStr);
},
cardinality: 1
}