71dd0033aa79534268f1fe6af9fb49da64da1761
[xtuple] / lib / enyo-x / source / widgets / number.js
1 /*jshint node:true, indent:2, curly:true, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true,
2 regexp:true, undef:true, trailing:true, white:true */
3 /*global XT:true, XV:true, Globalize:true, enyo:true, _:true */
4
5 (function () {
6
7   /**
8     @name XV.Number
9     @class An input control for validating and formatting string input that represent a number.<br />
10     The superkind of {@link XV.NumberWidget}.
11     @extends XV.Input
12    */
13   enyo.kind(
14     /** @lends XV.Number# */{
15     name: "XV.NumberWidget",
16     kind: "XV.InputWidget",
17     classes: "xv-numberwidget xv-input",
18     published: {
19       attr: null,
20       scale: 0,
21       formatting: true,
22       type: "number",
23       label: "",
24       showLabel: true
25     },
26     /**
27     @todo Document the setValue method.
28     */
29     setValue: function (value, options) {
30       // use isNaN here because this value could be a number String, 0 value, or null
31       // only want to set value as null in cases of bad strings and null/undefined
32       value = value !== null && !isNaN(value) ? XT.math.round(value, this.getScale()) : null;
33       XV.InputWidget.prototype.setValue.call(this, value, options);
34     },
35     /**
36       Determines whether the user input is numeric.
37       Validates value, whether set programatically or via user input. Gracefully handles
38       commas, periods, etc per the set culture using Globalize.
39
40       @param {String} Number (string) to be validated.
41       @return The value if it is valid, otherwise false.
42      */
43     validate: function (value) {
44       // this takes the string from the input field and parses it (including understanding commas, which isNaN cannot)
45       // if it cannot parse the value, it returns NaN
46       value = Globalize.parseFloat(value);
47
48       // use isNaN here because parseFloat could return NaN
49       // if you pass NaN into _.isNumber, it will misleadingly return true
50       // only bad string and null/undefined cases do we want to fail validation
51       return isNaN(value) ? false : value;
52     },
53     /**
54      @todo Document the valueChanged method.
55      */
56     valueChanged: function (value) {
57       // use isNaN here because this value could be a number String, 0 value, or null
58       // only in bad string and null/undefined cases do we want to return an empty string
59       if (!isNaN(value)) {
60         value = this.formatting ? Globalize.format(value, "n" + this.getScale()) : value;
61       } else {
62         value = "";
63       }
64       return XV.InputWidget.prototype.valueChanged.call(this, value);
65     }
66   });
67
68 }());