2

I'm trying to validate in a method that is setup to create products in a basic inventory, but numbers representing currency ie, 99 or 99.95 run through check() and Match.test() throw an match fail or return false:

check(_data, {
    name: String,
    sku: String,
    retail: Number,
    cost: Number,
    qty: Number
});

The mismatch makes sense when the field value is being passed as a string directly from the form field. The problem is that if I parseInt() or parseFloat() the field value and I enter a string like 'asdf' then these two functions discard the value making it look like nothing was entered.

How do I deal with Int and Float validation, including telling the user they have entered an invalid string instead of a number?

Ian Jones
  • 1,369
  • 1
  • 10
  • 15
  • possible duplicate of [Validate decimal numbers in JavaScript - IsNumeric()](http://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric) – David Weldon Feb 06 '15 at 04:53
  • Thanks, that is useful. The problem is that check() and Match.test() accept NaN as valid... so this means I have to then write extra logic? – Ian Jones Feb 06 '15 at 05:59

2 Answers2

1

The best way I can find to handle this is to use SimpleSchema

var productSchema = new SimpleSchema({
    name: {
        type: String,
        max: 64
    },
    sku: {
        type: String,
        max: 32
    },
    retail: {
        type: Number,
        decimal: true,
        min: 0
    },
    cost: {
        type: Number,
        decimal: true,
        min: 0
    },
    qty: {
        type: Number,
        min: 0
    }
});

Notice the decimal: true which handles floats. Combine simple schema with Collection2 and you have automatic validation handling on database insert and update.

Ian Jones
  • 1,369
  • 1
  • 10
  • 15
0

A little work around I'm using in the client event to clean the data, but I consider a hack:

parseNumber = function(n) {
    if(!isNaN(parseFloat(n)) && isFinite(n)) {
        return parseFloat(n);
    } else {
        return n
    }
}

This at least lets check() and Match.test() work by passing through either a valid number or an invalid string. Otherwise they don't handle NaN elegantly.

Ian Jones
  • 1,369
  • 1
  • 10
  • 15