1 // ==========================================================================
  2 // Project:   SproutCore - JavaScript Application Framework
  3 // Copyright: ©2006-2011 Strobe Inc. and contributors.
  4 //            Portions ©2008-2011 Apple Inc. All rights reserved.
  5 // License:   Licensed under MIT license (see license.js)
  6 // ==========================================================================
  7 
  8 sc_require('validators/validator') ;
  9 
 10 /**
 11   Handles parsing and validating of positive integers.
 12   
 13   @extends SC.Validator
 14   @author Nirumal Thomas
 15   @version 1.0
 16   @class
 17 */
 18 SC.Validator.PositiveInteger = SC.Validator.extend(
 19 /** @scope SC.Validator.PositiveInteger.prototype */ {
 20 
 21   /**
 22     Default Value to be displayed. If the value in the text field is null,
 23     undefined or an empty string, it will be replaced by this value.
 24 
 25     @property
 26     @type Number
 27     @default null
 28   */
 29   defaultValue: null,
 30 
 31   fieldValueForObject: function(object, form, field) {
 32     switch(SC.typeOf(object)) {
 33       case SC.T_NUMBER:
 34         object = object.toFixed(0) ;
 35         break ;
 36       case SC.T_NULL:
 37       case SC.T_UNDEFINED:
 38         object = this.get('defaultValue') ;
 39         break ;
 40     }
 41     return object ;
 42   },
 43 
 44   objectForFieldValue: function(value, form, field) {
 45     // strip out commas
 46     value = value.replace(/,/g,'');
 47     switch(SC.typeOf(value)) {
 48       case SC.T_STRING:
 49         if (value.length === 0) {
 50           value = this.get('defaultValue') ;
 51         } else {
 52           value = parseInt(value, 0) ;
 53         }
 54         break ;
 55       case SC.T_NULL:
 56       case SC.T_UNDEFINED:
 57         value = this.get('defaultValue') ;
 58         break ;
 59     }
 60     if(isNaN(value)) return this.get('defaultValue');
 61     return value ;
 62   },
 63 
 64   validate: function(form, field) {
 65     var value = field.get('fieldValue') ;
 66     return (value === '') || !isNaN(value) ;
 67   },
 68   
 69   validateError: function(form, field) {
 70     var label = field.get('errorLabel') || 'Field' ;
 71     return SC.$error(SC.String.loc("Invalid.Number(%@)", label), label) ;
 72   },
 73   
 74   /** 
 75     Allow only numbers
 76   */
 77   validateKeyDown: function(form, field, charStr) {
 78     var text = field.$input().val();
 79     if (!text) text='';
 80     text+=charStr;
 81     if(charStr.length===0) return true ;
 82     else return text.match(/^[0-9\0]*/)[0]===text;
 83   }
 84     
 85 }) ;
 86