I'm learning how to use Meteor and am currently looking at using the check package to validate user input, using the tutorial at: http://meteortips.com/first-meteor-tutorial/methods/.
I'm trying to use the Match.Integer pattern inside a method (addPlayer, say) to ensure data entered into a particular field (passed to the addPlayer method via the initialScore parameter) is a valid integer, which works fine when calling addPlayer through the console. However, when entering data via the form (which calls addPlayer when submitted) this doesn't work properly since the entered data is of the String type.
I was considering applying the Number function to the entered data before using Match.Integer but am thinking this is a bad idea since some non-numerical values would be accepted.
Would it be a good idea to have my own isInteger function, such as:
function isInteger(n) {
return n == +n && n == (n|0);
}
(from https://stackoverflow.com/a/3885844/3806231, but with === replaced with == to allow form data, of String type, to be checked)
and call this before applying the Number function as described above? For example:
Meteor.methods({
'addPlayer': function(initialScore) {
if (isInteger(initialScore)) {
check(Number(initialScore), Match.Integer);
}
}
});
Something like this seems quite long-winded and expensive just to validate an integer. Before using Meteor, I would just call something like the isInteger method, but now I'm using Meteor I want to make use of the available packages to save writing some of this standard validation code myself.
Is there a better way of doing this?