NumberTextBox.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. /*
  2. Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved.
  3. Available via Academic Free License >= 2.1 OR the modified BSD license.
  4. see: http://dojotoolkit.org/license for details
  5. */
  6. if(!dojo._hasResource["dijit.form.NumberTextBox"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
  7. dojo._hasResource["dijit.form.NumberTextBox"] = true;
  8. dojo.provide("dijit.form.NumberTextBox");
  9. dojo.require("dijit.form.ValidationTextBox");
  10. dojo.require("dojo.number");
  11. /*=====
  12. dojo.declare(
  13. "dijit.form.NumberTextBox.__Constraints",
  14. [dijit.form.RangeBoundTextBox.__Constraints, dojo.number.__FormatOptions, dojo.number.__ParseOptions], {
  15. // summary:
  16. // Specifies both the rules on valid/invalid values (minimum, maximum,
  17. // number of required decimal places), and also formatting options for
  18. // displaying the value when the field is not focused.
  19. // example:
  20. // Minimum/maximum:
  21. // To specify a field between 0 and 120:
  22. // | {min:0,max:120}
  23. // To specify a field that must be an integer:
  24. // | {fractional:false}
  25. // To specify a field where 0 to 3 decimal places are allowed on input:
  26. // | {places:'0,3'}
  27. });
  28. =====*/
  29. dojo.declare("dijit.form.NumberTextBoxMixin",
  30. null,
  31. {
  32. // summary:
  33. // A mixin for all number textboxes
  34. // tags:
  35. // protected
  36. // Override ValidationTextBox.regExpGen().... we use a reg-ex generating function rather
  37. // than a straight regexp to deal with locale (plus formatting options too?)
  38. regExpGen: dojo.number.regexp,
  39. /*=====
  40. // constraints: dijit.form.NumberTextBox.__Constraints
  41. // Despite the name, this parameter specifies both constraints on the input
  42. // (including minimum/maximum allowed values) as well as
  43. // formatting options like places (the number of digits to display after
  44. // the decimal point). See `dijit.form.NumberTextBox.__Constraints` for details.
  45. constraints: {},
  46. ======*/
  47. // value: Number
  48. // The value of this NumberTextBox as a Javascript Number (i.e., not a String).
  49. // If the displayed value is blank, the value is NaN, and if the user types in
  50. // an gibberish value (like "hello world"), the value is undefined
  51. // (i.e. get('value') returns undefined).
  52. //
  53. // Symmetrically, set('value', NaN) will clear the displayed value,
  54. // whereas set('value', undefined) will have no effect.
  55. value: NaN,
  56. // editOptions: [protected] Object
  57. // Properties to mix into constraints when the value is being edited.
  58. // This is here because we edit the number in the format "12345", which is
  59. // different than the display value (ex: "12,345")
  60. editOptions: { pattern: '#.######' },
  61. /*=====
  62. _formatter: function(value, options){
  63. // summary:
  64. // _formatter() is called by format(). It's the base routine for formatting a number,
  65. // as a string, for example converting 12345 into "12,345".
  66. // value: Number
  67. // The number to be converted into a string.
  68. // options: dojo.number.__FormatOptions?
  69. // Formatting options
  70. // tags:
  71. // protected extension
  72. return "12345"; // String
  73. },
  74. =====*/
  75. _formatter: dojo.number.format,
  76. _setConstraintsAttr: function(/*Object*/ constraints){
  77. var places = typeof constraints.places == "number"? constraints.places : 0;
  78. if(places){ places++; } // decimal rounding errors take away another digit of precision
  79. if(typeof constraints.max != "number"){
  80. constraints.max = 9 * Math.pow(10, 15-places);
  81. }
  82. if(typeof constraints.min != "number"){
  83. constraints.min = -9 * Math.pow(10, 15-places);
  84. }
  85. this.inherited(arguments, [ constraints ]);
  86. if(this.focusNode && this.focusNode.value && !isNaN(this.value)){
  87. this.set('value', this.value);
  88. }
  89. },
  90. _onFocus: function(){
  91. if(this.disabled){ return; }
  92. var val = this.get('value');
  93. if(typeof val == "number" && !isNaN(val)){
  94. var formattedValue = this.format(val, this.constraints);
  95. if(formattedValue !== undefined){
  96. this.textbox.value = formattedValue;
  97. }
  98. }
  99. this.inherited(arguments);
  100. },
  101. format: function(/*Number*/ value, /*dojo.number.__FormatOptions*/ constraints){
  102. // summary:
  103. // Formats the value as a Number, according to constraints.
  104. // tags:
  105. // protected
  106. var formattedValue = String(value);
  107. if(typeof value != "number"){ return formattedValue; }
  108. if(isNaN(value)){ return ""; }
  109. // check for exponential notation that dojo.number.format chokes on
  110. if(!("rangeCheck" in this && this.rangeCheck(value, constraints)) && constraints.exponent !== false && /\de[-+]?\d/i.test(formattedValue)){
  111. return formattedValue;
  112. }
  113. if(this.editOptions && this._focused){
  114. constraints = dojo.mixin({}, constraints, this.editOptions);
  115. }
  116. return this._formatter(value, constraints);
  117. },
  118. /*=====
  119. _parser: function(value, constraints){
  120. // summary:
  121. // Parses the string value as a Number, according to constraints.
  122. // value: String
  123. // String representing a number
  124. // constraints: dojo.number.__ParseOptions
  125. // Formatting options
  126. // tags:
  127. // protected
  128. return 123.45; // Number
  129. },
  130. =====*/
  131. _parser: dojo.number.parse,
  132. parse: function(/*String*/ value, /*dojo.number.__FormatOptions*/ constraints){
  133. // summary:
  134. // Replacable function to convert a formatted string to a number value
  135. // tags:
  136. // protected extension
  137. var v = this._parser(value, dojo.mixin({}, constraints, (this.editOptions && this._focused) ? this.editOptions : {}));
  138. if(this.editOptions && this._focused && isNaN(v)){
  139. v = this._parser(value, constraints); // parse w/o editOptions: not technically needed but is nice for the user
  140. }
  141. return v;
  142. },
  143. _getDisplayedValueAttr: function(){
  144. var v = this.inherited(arguments);
  145. return isNaN(v) ? this.textbox.value : v;
  146. },
  147. filter: function(/*Number*/ value){
  148. // summary:
  149. // This is called with both the display value (string), and the actual value (a number).
  150. // When called with the actual value it does corrections so that '' etc. are represented as NaN.
  151. // Otherwise it dispatches to the superclass's filter() method.
  152. //
  153. // See `dijit.form.TextBox.filter` for more details.
  154. return (value === null || value === '' || value === undefined) ? NaN : this.inherited(arguments); // set('value', null||''||undefined) should fire onChange(NaN)
  155. },
  156. serialize: function(/*Number*/ value, /*Object?*/ options){
  157. // summary:
  158. // Convert value (a Number) into a canonical string (ie, how the number literal is written in javascript/java/C/etc.)
  159. // tags:
  160. // protected
  161. return (typeof value != "number" || isNaN(value)) ? '' : this.inherited(arguments);
  162. },
  163. _setBlurValue: function(){
  164. var val = dojo.hitch(dojo.mixin({}, this, { _focused: true }), "get")('value'); // parse with editOptions
  165. this._setValueAttr(val, true);
  166. },
  167. _setValueAttr: function(/*Number*/ value, /*Boolean?*/ priorityChange, /*String?*/ formattedValue){
  168. // summary:
  169. // Hook so set('value', ...) works.
  170. if(value !== undefined && formattedValue === undefined){
  171. formattedValue = String(value);
  172. if(typeof value == "number"){
  173. if(isNaN(value)){ formattedValue = '' }
  174. // check for exponential notation that dojo.number.format chokes on
  175. else if(("rangeCheck" in this && this.rangeCheck(value, this.constraints)) || this.constraints.exponent === false || !/\de[-+]?\d/i.test(formattedValue)){
  176. formattedValue = undefined; // lets format comnpute a real string value
  177. }
  178. }else if(!value){ // 0 processed in if branch above, ''|null|undefined flow thru here
  179. formattedValue = '';
  180. value = NaN;
  181. }else{ // non-numeric values
  182. value = undefined;
  183. }
  184. }
  185. this.inherited(arguments, [value, priorityChange, formattedValue]);
  186. },
  187. _getValueAttr: function(){
  188. // summary:
  189. // Hook so get('value') works.
  190. // Returns Number, NaN for '', or undefined for unparsable text
  191. var v = this.inherited(arguments); // returns Number for all values accepted by parse() or NaN for all other displayed values
  192. // If the displayed value of the textbox is gibberish (ex: "hello world"), this.inherited() above
  193. // returns NaN; this if() branch converts the return value to undefined.
  194. // Returning undefined prevents user text from being overwritten when doing _setValueAttr(_getValueAttr()).
  195. // A blank displayed value is still returned as NaN.
  196. if(isNaN(v) && this.textbox.value !== ''){
  197. if(this.constraints.exponent !== false && /\de[-+]?\d/i.test(this.textbox.value) && (new RegExp("^"+dojo.number._realNumberRegexp(dojo.mixin({}, this.constraints))+"$").test(this.textbox.value))){ // check for exponential notation that parse() rejected (erroneously?)
  198. var n = Number(this.textbox.value);
  199. return isNaN(n) ? undefined : n; // return exponential Number or undefined for random text (may not be possible to do with the above RegExp check)
  200. }else{
  201. return undefined; // gibberish
  202. }
  203. }else{
  204. return v; // Number or NaN for ''
  205. }
  206. },
  207. isValid: function(/*Boolean*/ isFocused){
  208. // Overrides dijit.form.RangeBoundTextBox.isValid to check that the editing-mode value is valid since
  209. // it may not be formatted according to the regExp vaidation rules
  210. if(!this._focused || this._isEmpty(this.textbox.value)){
  211. return this.inherited(arguments);
  212. }else{
  213. var v = this.get('value');
  214. if(!isNaN(v) && this.rangeCheck(v, this.constraints)){
  215. if(this.constraints.exponent !== false && /\de[-+]?\d/i.test(this.textbox.value)){ // exponential, parse doesn't like it
  216. return true; // valid exponential number in range
  217. }else{
  218. return this.inherited(arguments);
  219. }
  220. }else{
  221. return false;
  222. }
  223. }
  224. }
  225. }
  226. );
  227. dojo.declare("dijit.form.NumberTextBox",
  228. [dijit.form.RangeBoundTextBox,dijit.form.NumberTextBoxMixin],
  229. {
  230. // summary:
  231. // A TextBox for entering numbers, with formatting and range checking
  232. // description:
  233. // NumberTextBox is a textbox for entering and displaying numbers, supporting
  234. // the following main features:
  235. //
  236. // 1. Enforce minimum/maximum allowed values (as well as enforcing that the user types
  237. // a number rather than a random string)
  238. // 2. NLS support (altering roles of comma and dot as "thousands-separator" and "decimal-point"
  239. // depending on locale).
  240. // 3. Separate modes for editing the value and displaying it, specifically that
  241. // the thousands separator character (typically comma) disappears when editing
  242. // but reappears after the field is blurred.
  243. // 4. Formatting and constraints regarding the number of places (digits after the decimal point)
  244. // allowed on input, and number of places displayed when blurred (see `constraints` parameter).
  245. baseClass: "dijitTextBox dijitNumberTextBox"
  246. }
  247. );
  248. }