Tips and tricks #14: How to use a masked input
This article describes how to use a masked input in your calculators
Tips and tricks series
- Tips and tricks #1: How to set output value
- Tips and tricks #2: How to make calculator translatable into different languages
- Tips and tricks #3: How to make calculator with custom errors
- Tips and tricks #4: How to make calculator with table output
- Tips and tricks #5: How to show/hide input and output controls in a calculator
- Tips and tricks #6: How to make calculator with virtual keyboard
- Tips and tricks #7: How to make calculator with SVG image map
- Tips and tricks #8: How to reuse existing calculator
- Tips and tricks #9: Big numbers
- Tips and tricks #10: Files, long calculation mode
- Tips and tricks #11: Dynamic table columns
- Tips and tricks #12: Long (infinite) calculations
- Tips and tricks #13: Bitmaps and Pixel manipulation
- Tips and tricks #14: How to use a masked input
This article may rely on knowledge you should get from previous articles, so you may want to check them first.
Our engine supports so-called "masked input", which allows user to more easily enter fixed width input for data in a certain format (like phone numbers and dates). We use the jquery.maskedinput plugin for that purpose. While you can refer to the original documentation, here are the things you need to know to use it for the calculators on this site.
Supported mask definitions
- a - Represents an alpha character (A-Z,a-z)
- 9 - Represents a numeric character (0-9)
- * - Represents an alphanumeric character (A-Z,a-z,0-9)
Input settings
When you are adding masked input to your calculator, you can configure the following settings in the Input editor dialog:
Type: Masked input
Default value: Should conform to the mask
Mask: According to supported mask definitions, see above
Placeholder: The string to be displayed if there is no default value or you have cleared it. Should conform to the mask in general.
The calculator below gives an example of such input - in the Date form field. Here are the settings:
Type: Masked input
Default value: 31.12.2014 00:00:00
Mask: 99.99.9999 99:99:99
Placeholder: DD.MM.YYYY hh:mm:ss
Handling the input value
You receive the input value as a string. Usually you grab the interesting parts using the Regex expression, because you know the format.
const expr = new RegExp("(\\d{2})\\.(\\d{2})\\.(\\d{4})\\s(\\d{2}):(\\d{2}):(\\d{2})", "g");
if (!expr.test(datePoint)) throw { "source" : "datePoint", "message" : messages[ "bad" ] };
expr.lastIndex = 0;
const matches = expr.exec(datePoint);
const point = new Date(Number(matches[3]), Number(matches[2])-1, Number(matches[1]), Number(matches[4]), Number(matches[5]), Number(matches[6]), 0);
Of course with the example above one can enter a meaningless date, like 99.99.9999 99:99:99, so, for this case, it is also a good idea to validate the value you got.
commentaires