Better/working iMask support
See original GitHub issueIn 2.x i added a quick support for iMask in src/string.js
But I have discovered that iMask config format isn’t very JSON-format friendly, as the mask can be a string, date object, number object, custom imask object, function or regular expression.
So the current implementation in JSON-Editor is really crippled as you can’t use the complex masking types.
Example of an iMask mask config:
mask: [
{
mask: 'RGB,RGB,RGB',
blocks: {
RGB: {
mask: IMask.MaskedRange,
from: 0,
to: 255
}
}
},
{
mask: /^#[0-9a-f]{0,6}$/i
}
]
The only solution (without having to create a new format) I could come up with was to convert all the non-JSON objects/regex/functions to strings, like this:
"mask": [{
"mask": "RGB,RGB,RGB",
"blocks": {
"RGB": {
"mask": "IMask.MaskedRange",
"from": 0,
"to": 255
}
}
},
{
"mask": "/^#[0-9a-f]{0,6}$/i"
}]
And then in src/string.js, “translate” the mask strings back to the correct object/regex (Callback system handles the function masks)
ajustIMaskOptions: function (obj) {
// iMask config format is not JSON friendly, so function and regex based mask
// properties have to be adjusted from string to the correct format
var regExMatch
for (var prop in obj) {
if (obj[prop] === Object(obj[prop])) obj[prop] = this.ajustIMaskOptions(obj[prop])
else if (prop === 'mask') {
regExMatch = obj[prop].match(/^\/(.*)\/([gimsuy]*)$/)
if (regExMatch) obj[prop] = new RegExp(regExMatch[1], regExMatch[2])
else if (obj[prop] === 'Number') obj[prop] = window.Number
else if (obj[prop] === 'Date') obj[prop] = window.Date
else if (obj[prop] === 'IMask.MaskedEnum') obj[prop] = window.IMask.MaskedEnum
else if (obj[prop] === 'IMask.MaskedRange') obj[prop] = window.IMask.MaskedRange
}
}
return obj
},
Drawback is that you can’t use “Number”, “Date”, “IMask.MaskedEnum” and “IMask.MaskedRange” as string patterns (But who would need that?) or string patterns starting and ending with “/” (with optional modifiers) which will be turned into regular expressions.
Anyone got a better solution/idea before I create a PR?
Issue Analytics
- State:
- Created 4 years ago
- Comments:7
Top GitHub Comments
@pmk65 the best option IMO is to force user to define the regexp explicitly, something like a “regexp:” prefix. So you can check if is intended to be a regexp through strValue.indexOf(‘regexp:’) === 0
instead of dealing with RegExp I think it is better to check against the window object: (this also gives developers a free bonus so they can use any custom mask defined under the IMask namespace or whatever namespace they want).
see https://codepen.io/intco/pen/NWWvWNr for some quick tests
please note also that the syntax “for var prop in obj” is not the correct way to cycle object properties if you do not need to access the prototype chain.
https://stackoverflow.com/questions/40335779/are-there-any-cases-when-i-should-use-the-in-operator-instead-of-hasownproperty